import*as e from"../../models/trace/trace.js";import*as t from"../../ui/legacy/theme_support/theme_support.js";import*as i from"../../core/i18n/i18n.js";import*as n from"../../core/sdk/sdk.js";import*as r from"../../models/timeline_model/timeline_model.js";import*as a from"../../core/common/common.js";import*as s from"../../core/platform/platform.js";import*as o from"../../core/root/root.js";import*as l from"../../models/bindings/bindings.js";import*as d from"../../ui/legacy/components/perf_ui/perf_ui.js";import*as c from"../../ui/legacy/legacy.js";import*as h from"../../models/source_map_scopes/source_map_scopes.js";import*as m from"../../ui/legacy/components/utils/utils.js";import*as u from"../../core/host/host.js";import*as p from"../../ui/components/panel_feedback/panel_feedback.js";import*as g from"../mobile_throttling/mobile_throttling.js";import*as v from"../../models/text_utils/text_utils.js";import*as T from"../../ui/legacy/components/data_grid/data_grid.js";import*as f from"../layer_viewer/layer_viewer.js";const w={sSelfS:"{PH1} (self {PH2})"},y=i.i18n.registerUIStrings("panels/timeline/AppenderUtils.ts",w),S=i.i18n.getLocalizedString.bind(void 0,y);function b(e){const i={padding:4,height:17,collapsible:!0,color:t.ThemeSupport.instance().getComputedValue("--color-text-primary"),backgroundColor:t.ThemeSupport.instance().getComputedValue("--color-background"),nestingLevel:0,shareHeaderLine:!0};return Object.assign(i,e)}function C(e,t,i,n,r,a){const s={startLevel:e,name:t,style:i,selectable:n,expanded:r};return n&&a&&(s.track=a),s}function k(t,n){const r=e.Helpers.Timing.microSecondsToMilliseconds(t||0);if(r===e.Types.Timing.MilliSeconds(0))return"";const a=e.Helpers.Timing.microSecondsToMilliseconds(n||0),s=1e-6;return Math.abs(r-a)>s&&a>s?S(w.sSelfS,{PH1:i.TimeUtilities.millisToString(r,!0),PH2:i.TimeUtilities.millisToString(a,!0)}):i.TimeUtilities.millisToString(r,!0)}function P(e,t){let i=0;const n=e.ts,r=e.ts+(e.dur||0);for(;i<t.length&&n<t[i];)++i;return t[i]=r,i}var M=Object.freeze({__proto__:null,buildGroupStyle:b,buildTrackHeader:C,getFormattedTime:k,getEventLevel:P});class E{x;y;width;height;color;outlineColor;constructor([e,t,i,n]){this.x=e,this.y=t,this.width=i,this.height=n,this.color={r:238,g:111,b:99,a:.4},this.outlineColor={r:238,g:111,b:99,a:.7}}}let x;class I{static instance(e={forceNew:null}){const{forceNew:t}=e;return x&&!t||(x=new I),x}linkify(e,t){const i=document.createElement("span"),r=e,{x:a,y:s,width:o,height:l}=r;return i.textContent=`Location: [${a},${s}], Size: [${o}x${l}]`,i.addEventListener("mouseover",(()=>n.OverlayModel.OverlayModel.highlightRect(r))),i.addEventListener("mouseleave",(()=>n.OverlayModel.OverlayModel.clearHighlight())),i}}var L=Object.freeze({__proto__:null,CLSRect:E,Linkifier:I});const R=new CSSStyleSheet;R.replaceSync(".timeline-flamechart-popover{overflow:hidden}.timeline-flamechart-popover span{margin-right:5px}.timeline-flamechart-popover span.timeline-info-network-time{color:var(--color-primary-old)}.timeline-flamechart-popover span.timeline-info-time{color:var(--color-accent-green)}.timeline-flamechart-popover span.timeline-info-warning{color:var(--color-accent-red)}.timeline-flamechart-popover span.timeline-info-warning *{color:inherit}\n/*# sourceURL=timelineFlamechartPopover.css */\n");const F=new CSSStyleSheet;F.replaceSync(".header,\n.children,\n.content{min-height:initial;line-height:initial}.children li::before{display:none}.content{margin-bottom:4px}.content .stack-preview-container{margin-left:8px}.content .node-list{margin-left:10px}.tree-outline li{white-space:normal}\n/*# sourceURL=invalidationsTree.css */\n");const D=new CSSStyleSheet;D.replaceSync(".image-preview-container{background:transparent;text-align:center;border-spacing:0}.image-preview-container img{margin:6px 0;max-width:100px;max-height:100px;background-image:var(--image-file-checker);user-select:text;vertical-align:top;-webkit-user-drag:auto}.image-container{padding:0}.image-container > div{min-height:50px;display:flex;align-items:center;justify-content:center;cursor:pointer}.image-preview-container .row{line-height:1.2;vertical-align:baseline}.image-preview-container .title{padding-right:0.5em;text-align:right;color:var(--color-text-secondary);white-space:nowrap}.image-preview-container .description{white-space:nowrap;text-align:left;color:var(--color-text-primary)}.image-preview-container .description-link{max-width:20em}.image-preview-container .source-link{white-space:normal;word-break:break-all;color:var(--color-link);cursor:pointer}\n/*# sourceURL=imagePreview.css */\n");const U=new CSSStyleSheet;U.replaceSync('.content{margin-left:5px}.history-dropdown-button{width:160px;height:26px;text-align:left;display:flex;border:1px solid transparent}.history-dropdown-button[disabled]{opacity:50%;border:1px solid transparent}.history-dropdown-button > .content{padding-right:5px;overflow:hidden;text-overflow:ellipsis;flex:1 1;min-width:35px}.history-dropdown-button:focus-visible::before{content:"";position:absolute;top:2px;left:0;right:0;bottom:2px;border-radius:2px;background:var(--divider-line)}@media (forced-colors: active){.history-dropdown-button[disabled]{opacity:100%}.history-dropdown-button[disabled] [is="ui-icon"].icon-mask{background-color:GrayText}}\n/*# sourceURL=historyToolbarButton.css */\n');const H=new CSSStyleSheet;H.replaceSync('.timeline-toolbar-container{display:flex;flex:none}.timeline-toolbar-container > .toolbar{background-color:var(--color-background-elevation-1);border-bottom:var(--legacy-divider-border)}.timeline-main-toolbar{flex:1 1 auto}.timeline-settings-pane{flex:none;background-color:var(--color-background-elevation-1);border-bottom:var(--legacy-divider-border)}#timeline-overview-panel{flex:none;position:relative;border-bottom:1px solid var(--color-details-hairline)}#timeline-overview-grid{background-color:var(--color-background)}#timeline-overview-grid .timeline-grid-header{height:12px}#timeline-overview-grid .resources-dividers-label-bar{pointer-events:auto;height:12px}#timeline-overview-grid .resources-divider-label{top:1px}.timeline-details-split{flex:auto}.timeline.panel .status-pane-container{z-index:1000;display:flex;align-items:center;pointer-events:none}.timeline.panel .status-pane-container.tinted{background-color:var(--color-background-elevation-2);pointer-events:auto}#timeline-overview-panel .overview-strip{margin-top:2px;justify-content:center}#timeline-overview-panel .overview-strip .timeline-overview-strip-title{color:var(--color-text-secondary);font-size:10px;font-weight:bold;z-index:100;background-color:var(--color-background-opacity-80);padding:0 4px;position:absolute;top:-2px;right:0}#timeline-overview-cpu-activity{flex-basis:20px}#timeline-overview-network{flex-basis:8px}#timeline-overview-filmstrip{flex-basis:30px}#timeline-overview-memory{flex-basis:20px}#timeline-overview-network::before,\n#timeline-overview-cpu-activity::before{content:"";position:absolute;left:0;right:0;bottom:0;border-bottom:1px solid var(--divider-line);z-index:-200}.overview-strip .background{z-index:-10}#timeline-overview-responsiveness{flex-basis:5px;margin-top:0!important}#timeline-overview-input{flex-basis:6px}#timeline-overview-pane{flex:auto;position:relative;overflow:hidden}#timeline-overview-container{display:flex;flex-direction:column;flex:none;position:relative;overflow:hidden}#timeline-overview-container canvas{width:100%;height:100%}.popover ul{margin:0;padding:0;list-style-type:none}.memory-graph-label{position:absolute;right:0;bottom:0;font-size:9px;color:var(--color-text-secondary);white-space:nowrap;padding:0 4px;background-color:var(--color-background-opacity-80)}#memory-graphs-canvas-container{overflow:hidden;flex:auto;position:relative}#memory-counters-graph{flex:auto}#memory-graphs-canvas-container .memory-counter-marker{position:absolute;border-radius:3px;width:5px;height:5px;margin-left:-3px;margin-top:-2px}#memory-graphs-container .timeline-memory-header{flex:0 0 26px;background-color:var(--color-background-elevation-1);border-bottom:1px solid var(--color-details-hairline);justify-content:space-between}#memory-graphs-container .timeline-memory-header::after{content:"";background-image:var(--image-file-toolbarResizerVertical);background-repeat:no-repeat;background-position:right center,center;flex:20px 0 0;margin:0 4px}.timeline-memory-toolbar{flex-shrink:1}.memory-counter-value{margin:8px}#counter-values-bar{flex:0 0 20px;border-top:solid 1px var(--color-details-hairline);width:100%;overflow:hidden;line-height:18px}#timeline-overview-coverage{flex-basis:20px}.timeline-overview-coverage-label{position:absolute;right:0;bottom:0;font-size:9px;color:var(--color-text-secondary);white-space:nowrap;padding:0 4px;background-color:var(--color-background-opacity-80)}.timeline-details{vertical-align:top}.timeline-details-view{color:var(--color-text-secondary);overflow:hidden}.timeline-details-view-body{flex:auto;overflow:auto;position:relative;background-color:var(--color-background-elevation-1);user-select:text}.timeline-details-view-block{flex:none;display:flex;background-color:var(--color-background);flex-direction:column;padding-bottom:5px;border-bottom:var(--legacy-divider-border)}.timeline-details-view-row{padding-left:10px;line-height:20px}.timeline-details-view-block .timeline-details-stack-values{flex-direction:column!important}.timeline-details-chip-title{font-size:13px;padding:8px;display:flex;align-items:center}.timeline-details-view-row-title:not(:empty){color:var(--color-text-secondary);overflow:hidden;padding-right:10px;display:inline-block}.timeline-details-warning{--override-details-warning-background-color:rgb(250 209 209/48%);background-color:var(--override-details-warning-background-color)}.-theme-with-dark-background .timeline-details-warning,\n:host-context(.-theme-with-dark-background) .timeline-details-warning{--override-details-warning-background-color:rgb(87 10 10/48%)}.timeline-details-warning .timeline-details-view-row-title{color:var(--color-red)}.timeline-details-view-row-value{display:inline-block;user-select:text;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}.timeline-details-warning .timeline-details-view-row-value{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.timeline-details-view-row-value .stack-preview-container{line-height:11px}.timeline-details-view-pie-chart-wrapper{margin:4px 0}.timeline-details-view-pie-chart{margin-top:5px}.timeline-details-view-row-stack-trace{padding:4px 0;line-height:inherit}.timeline-flamechart{overflow:hidden}.timeline-flamechart-resizer{flex:8px 0 0;background-color:var(--color-background-elevation-1);border:1px var(--color-details-hairline);border-style:solid none;display:flex;flex-direction:row;align-items:flex-end;justify-content:center}.timeline-network-resizer-disabled > .timeline-flamechart-resizer{display:none}.timeline-flamechart-resizer::after{content:"...";font-size:14px;margin-bottom:-1px}.timeline-layers-view-properties table{width:100%;border-collapse:collapse}.timeline-layers-view-properties td{border:1px solid var(--color-details-hairline);line-height:22px}.timeline-filmstrip-preview > img{margin-top:5px;max-width:500px;max-height:300px;cursor:pointer;border:1px solid var(--color-details-hairline)}.timeline-tree-view{display:flex;overflow:hidden}.timeline-tree-view .toolbar{background-color:var(--color-background-elevation-1);border-bottom:var(--legacy-divider-border)}.timeline-tree-view .data-grid{border:none;flex:auto}.timeline-tree-view .data-grid .data-container{overflow-y:scroll}.timeline-tree-view .data-grid.data-grid-fits-viewport .corner{display:table-cell}.timeline-tree-view .data-grid table.data{background:var(--color-background)}.timeline-tree-view .data-grid tr:hover td:not(.bottom-filler-td){background-color:var(--color-background-hover-overlay)}.timeline-tree-view .data-grid td.numeric-column{text-align:right;position:relative}.timeline-tree-view .data-grid div.background-percent-bar{float:right}.timeline-tree-view .data-grid span.percent-column{color:var(--color-text-secondary);width:45px;display:inline-block}.timeline-tree-view .data-grid tr.selected span{color:inherit}.timeline-tree-view .data-grid .name-container{display:flex;align-items:center;padding-left:2px}.timeline-tree-view .data-grid .name-container .activity-icon{width:12px;height:12px;border:1px solid var(--divider-line);margin:3px 0}.timeline-tree-view .data-grid .name-container .activity-icon-container{margin-right:3px;display:flex;flex-wrap:wrap;align-items:center;justify-content:center;width:18px;height:18px;overflow:hidden}.timeline-tree-view .data-grid .name-container .activity-warning::after{content:"[deopt]";margin:0 4px;line-height:12px;font-size:10px;color:var(--color-text-disabled)}.timeline-tree-view .data-grid tr.selected .name-container .activity-warning::after{color:var(--color-text-secondary-selected)}.timeline-tree-view .data-grid .name-container .activity-link{flex:auto;text-align:right;overflow:hidden;text-overflow:ellipsis;margin-left:5px}.timeline-tree-view .data-grid .background-bar-container{position:absolute;left:3px;right:0}.timeline-tree-view .data-grid .background-bar{--override-background-bar-background-color:hsl(43deg 84% 64%/20%);--override-background-bar-border-color:hsl(43deg 84% 64%);float:right;height:18px;background-color:var(--override-background-bar-background-color);border-bottom:1px solid var(--override-background-bar-border-color)}.timeline-tree-view .data-grid .selected .background-bar{background-color:var(--color-background-opacity-50);border-bottom:1px solid var(--color-background-opacity-80)}.-theme-with-dark-background .timeline-tree-view .data-grid .background-bar,\n:host-context(.-theme-with-dark-background) .timeline-tree-view .data-grid .background-bar{--override-background-bar-background-color:rgb(169 126 15/20%);--override-background-bar-border-color:rgb(169 126 15)}.timeline-tree-view .timeline-details-view-body .full-widget-dimmed-banner{background-color:inherit}.timeline-details .filter-input-field{width:120px}.timeline-tree-view .data-grid thead{height:21px}.timeline-stack-view-header{height:27px;background-color:var(--color-background-elevation-1);padding:6px 10px;color:var(--color-text-secondary);white-space:nowrap;border-bottom:var(--legacy-divider-border)}.timeline-landing-page{position:absolute;background-color:var(--color-background);justify-content:center;align-items:center;overflow:auto;font-size:13px;color:var(--color-text-secondary)}@media (forced-colors: active){.timeline-tree-view .data-grid .name-container .activity-icon{forced-color-adjust:none}.timeline-tree-view .data-grid tr.selected span.percent-column,\n  .timeline-tree-view .data-grid tr.selected div.background-percent-bar span,\n  .timeline-tree-view .data-grid tr.selected .name-container .activity-link .devtools-link{color:HighlightText}.timeline-tree-view .data-grid .background-bar,\n  .timeline-tree-view .data-grid tr:hover td:not(.bottom-filler-td){background-color:transparent}.timeline-tree-view .data-grid tr.selected .background-bar{background-color:transparent;border-bottom-color:HighlightText}}.timeline-additional-metrics{display:flex;flex:0 0 27px;background-color:var(--color-background-elevation-1);border-top:var(--legacy-divider-border);overflow:hidden;z-index:100}.timeline-details-view-row-stack-trace div{white-space:nowrap;text-overflow:ellipsis;line-height:12px}.timeline-details-view-body > div{overflow-y:hidden;overflow-x:auto}.timeline-landing-page > div{max-width:450px;margin:10px}.timeline-details-chip-title > div{width:12px;height:12px;border:1px solid var(--color-details-hairline);display:inline-block;margin-right:4px;content:" "}.timeline-paint-profiler-log-split > div:last-child{background-color:var(--color-background-elevation-1);z-index:0}.timeline-layers-view > div:last-child,\n.timeline-layers-view-properties > div:last-child{background-color:var(--color-background-elevation-1)}.timeline.panel .status-pane-container > div{pointer-events:auto}.timeline-landing-page > div > p{flex:none;white-space:pre-line;line-height:18px}.timeline-tree-view .data-grid .name-container div{flex:none}.status-pane-container > .small-dialog{width:100%;height:100%}.timeline-concurrency-input{width:50px}.timeline-concurrency-hidden{visibility:hidden}devtools-feedback-button{float:right}\n/*# sourceURL=timelinePanel.css */\n');const N=new CSSStyleSheet;N.replaceSync(".timeline-status-dialog{display:flex;flex-direction:column;padding:16px 16px 12px;align-self:center;background-color:var(--color-background);box-shadow:var(--drop-shadow)}.status-dialog-line{margin:2px;height:14px;min-height:auto;display:flex;align-items:baseline}.status-dialog-line .label{display:inline-block;width:80px;text-align:right;color:var(--color-text-primary);margin-right:10px}.timeline-status-dialog .progress .indicator-container{display:inline-block;width:200px;height:8px;background-color:var(--color-background-elevation-2)}.timeline-status-dialog .progress .indicator{background-color:var(--color-primary-variant);height:100%;width:0;margin:0}.timeline-status-dialog .stop-button{margin-top:8px;height:100%;align-self:flex-end}.timeline-status-dialog .stop-button button{min-width:80px}.timeline-status-dialog.small-dialog{width:inherit;justify-content:center}.small-dialog > .stop-button{align-self:center;margin-top:20px;height:initial}@media (forced-colors: active){.timeline-status-dialog{border:1px solid canvastext}.timeline-status-dialog .progress .indicator-container{border:1px solid ButtonText;background-color:ButtonFace}.timeline-status-dialog .progress .indicator{forced-color-adjust:none;background-color:ButtonText}}\n/*# sourceURL=timelineStatusDialog.css */\n");const A={cpuProfileForATargetIsNot:"CPU profile for a target is not available.",tracingNotSupported:"Performance trace recording not supported for this type of target"},B=i.i18n.registerUIStrings("panels/timeline/TimelineController.ts",A),W=i.i18n.getLocalizedString.bind(void 0,B);class V{target;tracingManager;performanceModel;client;tracingModel;tracingCompleteCallback;profiling;cpuProfiles;constructor(e,t){this.target=e,this.tracingManager=e.model(n.TracingManager.TracingManager),this.performanceModel=new bt,this.performanceModel.setMainTarget(e),this.client=t,this.tracingModel=new n.TracingModel.TracingModel,n.TargetManager.TargetManager.instance().observeModels(n.CPUProfilerModel.CPUProfilerModel,this)}dispose(){n.TargetManager.TargetManager.instance().unobserveModels(n.CPUProfilerModel.CPUProfilerModel,this)}mainTarget(){return this.target}async startRecording(e){function t(e){return"disabled-by-default-"+e}const i=[o.Runtime.experiments.isEnabled("timelineShowAllEvents")?"*":"-*",r.TimelineModel.TimelineModelImpl.Category.Console,r.TimelineModel.TimelineModelImpl.Category.UserTiming,"devtools.timeline",t("devtools.timeline"),t("devtools.timeline.frame"),t("devtools.timeline.stack"),t("v8.compile"),t("v8.cpu_profiler.hires"),r.TimelineModel.TimelineModelImpl.Category.Loading,t("lighthouse"),"v8.execute","v8"];o.Runtime.experiments.isEnabled("timelineV8RuntimeCallStats")&&e.enableJSSampling&&i.push(t("v8.runtime_stats_sampling")),e.enableJSSampling&&i.push(t("v8.cpu_profiler")),o.Runtime.experiments.isEnabled("timelineInvalidationTracking")&&i.push(t("devtools.timeline.invalidationTracking")),e.capturePictures&&i.push(t("devtools.timeline.layers"),t("devtools.timeline.picture"),t("blink.graphics_context_annotations")),e.captureFilmStrip&&i.push(t("devtools.screenshot")),this.performanceModel.setRecordStartTime(Date.now());const a=await this.startRecordingWithCategories(i.join(","));return a.getError()&&(await this.waitForTracingToStop(!1),await n.TargetManager.TargetManager.instance().resumeAllTargets()),a}async stopRecording(){return this.tracingManager&&this.tracingManager.stop(),this.client.loadingStarted(),await this.waitForTracingToStop(!0),await this.allSourcesFinished(),this.performanceModel}getPerformanceModel(){return this.performanceModel}async waitForTracingToStop(e){const t=[];this.tracingManager&&e&&t.push(new Promise((e=>{this.tracingCompleteCallback=e}))),t.push(this.stopProfilingOnAllModels()),await Promise.all(t)}modelAdded(e){this.profiling&&e.startRecording()}modelRemoved(e){}addCpuProfile(e,t){t?(this.cpuProfiles||(this.cpuProfiles=new Map),this.cpuProfiles.set(e,t)):a.Console.Console.instance().warn(W(A.cpuProfileForATargetIsNot))}async stopProfilingOnAllModels(){const e=this.profiling?n.TargetManager.TargetManager.instance().models(n.CPUProfilerModel.CPUProfilerModel):[];this.profiling=!1;const t=[];for(const i of e){const e=i.target().id(),n=i.stopRecording().then(this.addCpuProfile.bind(this,e));t.push(n)}await Promise.all(t)}async startRecordingWithCategories(e){if(!this.tracingManager)throw new Error(A.tracingNotSupported);return await n.TargetManager.TargetManager.instance().suspendAllTargets("performance-timeline"),this.tracingManager.start(this,e,"")}traceEventsCollected(e){this.tracingModel.addEvents(e)}tracingComplete(){this.tracingCompleteCallback&&(this.tracingCompleteCallback(void 0),this.tracingCompleteCallback=null)}async allSourcesFinished(){this.client.processingStarted(),await this.finalizeTrace()}async finalizeTrace(){this.injectCpuProfileEvents(),await n.TargetManager.TargetManager.instance().resumeAllTargets(),this.tracingModel.tracingComplete(),await this.client.loadingComplete(this.tracingModel,null),this.client.loadingCompleteForTest()}injectCpuProfileEvent(e,t,i){if(!i)return;const a={cat:n.TracingModel.DevToolsMetadataEventCategory,ph:"I",ts:1e3*this.tracingModel.maximumRecordTime(),pid:e,tid:t,name:r.TimelineModel.RecordType.CpuProfile,args:{data:{cpuProfile:i}}};this.tracingModel.addEvents([a])}buildTargetToProcessIdMap(){const e=r.TimelineModel.TimelineModelImpl.DevToolsMetadataEvent,t=this.tracingModel.devToolsMetadataEvents(),i=t.find((t=>t.name===e.TracingStartedInBrowser));if(!i)return null;const a=new s.MapUtilities.Multimap,o=new Map,l=i.args.data.frames;for(const e of l)o.set(e.frame,e.processId);for(const i of t){const t=i.args.data;switch(i.name){case e.FrameCommittedInBrowser:t.processId?o.set(t.frame,t.processId):a.set(t.processPseudoId,t.frame);break;case e.ProcessReadyInBrowser:for(const e of a.get(t.processPseudoId)||[])o.set(e,t.processId)}}const d=l.find((e=>!e.parent)).processId,c=this.tracingModel.getProcessById(d);if(c){const e=n.TargetManager.TargetManager.instance().primaryPageTarget();e&&o.set(e.id(),c.id())}return o}injectCpuProfileEvents(){if(!this.cpuProfiles)return;const e=r.TimelineModel.TimelineModelImpl.DevToolsMetadataEvent,t=this.tracingModel.devToolsMetadataEvents(),i=this.buildTargetToProcessIdMap();if(i)for(const[e,t]of this.cpuProfiles){const n=i.get(e);if(!n)continue;const a=this.tracingModel.getProcessById(n),s=a&&a.threadByName(r.TimelineModel.TimelineModelImpl.RendererMainThreadName);s&&this.injectCpuProfileEvent(n,s.id(),t)}else{const i=t.filter((t=>t.name===e.TracingStartedInPage)),a=i[i.length-1];if(a){const e=a.thread.process().id();if(this.tracingManager){const t=this.cpuProfiles.get(this.tracingManager.target().id());this.injectCpuProfileEvent(e,a.thread.id(),t)}}else{let e=0;for(const t of this.cpuProfiles){const i=n.TargetManager.TargetManager.instance().targetById(t[0]),a=i&&i.name();this.tracingModel.addEvents(r.TimelineJSProfile.TimelineJSProfileProcessor.createFakeTraceFromCpuProfile(t[1],++e,1===e,a))}}}const a=t.filter((t=>t.name===e.TracingSessionIdForWorker));for(const e of a){const t=e.args.data.workerId,i=this.cpuProfiles.get(t);this.injectCpuProfileEvent(e.thread.process().id(),e.args.data.workerThreadId,i)}this.cpuProfiles=null}tracingBufferUsage(e){this.client.recordingProgress(e)}eventsRetrievalProgress(e){this.client.loadingProgress(e)}}var O=Object.freeze({__proto__:null,TimelineController:V});const z={net:"NET",cpu:"CPU",heap:"HEAP",sSDash:"{PH1} – {PH2}"},G=i.i18n.registerUIStrings("panels/timeline/TimelineEventOverview.ts",z),_=i.i18n.getLocalizedString.bind(void 0,G);class j extends d.TimelineOverviewPane.TimelineOverviewBase{model;constructor(e,t){super(),this.element.id="timeline-overview-"+e,this.element.classList.add("overview-strip"),this.model=null,t&&(this.element.createChild("div","timeline-overview-strip-title").textContent=t)}setModel(e){this.model=e}renderBar(e,t,i,n,r){const a=e,s=t-e,o=this.context();o.fillStyle=r,o.fillRect(a,i,s,n)}}class q extends j{constructor(){super("network",_(z.net))}update(){if(super.update(),!this.model)return;const e=this.model.timelineModel(),t=this.height()/2,i=e.minimumRecordTime(),n=e.maximumRecordTime()-i,r=this.width(),a=r/n,s=new Path2D,o=new Path2D,l=new Set(["VeryHigh","High","Medium"]);for(const n of e.networkRequests()){const e=l.has(n.priority)?s:o,d=Math.max(Math.floor((n.startTime-i)*a),0),c=Math.min(Math.ceil((n.endTime-i)*a+1),r);e.rect(d,0,c-d,t-1)}const d=this.context();d.save(),d.fillStyle="hsl(214, 60%, 60%)",d.fill(s),d.translate(0,t),d.fillStyle="hsl(214, 80%, 80%)",d.fill(o),d.restore()}}const J=new WeakMap;class $ extends j{backgroundCanvas;constructor(){super("cpu-activity",_(z.cpu)),this.backgroundCanvas=this.element.createChild("canvas","fill background")}resetCanvas(){super.resetCanvas(),this.backgroundCanvas.width=this.element.clientWidth*window.devicePixelRatio,this.backgroundCanvas.height=this.element.clientHeight*window.devicePixelRatio}update(){if(super.update(),!this.model)return;const e=this.model.timelineModel(),t=4*window.devicePixelRatio,i=this.width(),a=this.height(),s=a,o=e.minimumRecordTime(),l=e.maximumRecordTime()-o,d=t/(i/l),c=ct.categories(),h=ct.getTimelineMainEventCategories(),m=h.indexOf("other");console.assert(0===h.indexOf("idle"));for(let e=0;e<h.length;++e)J.set(c[h[e]],e);const u=this.backgroundCanvas.getContext("2d");if(!u)throw new Error("Could not find 2d canvas");for(const t of e.tracks())t.type===r.TimelineModel.TrackType.MainThread&&t.forMainFrame?p(this.context(),t.events):p(u,t.events);function p(e,u){const p=new Z(o,d,(function(e){let i=s;for(let n=1;n<h.length;++n){const r=(e[n]||0)/d*a;i-=r,T[n].bezierCurveTo(g,f[n],g,i,g+t/2,i),f[n]=i}g+=t}));let g=0;const v=[],T=[],f=[];for(let e=0;e<h.length;++e)T[e]=new Path2D,T[e].moveTo(0,a),f[e]=a;r.TimelineModel.TimelineModelImpl.forEachEvent(u,(function(e){const{startTime:t}=n.TracingModel.timesForEventInMilliseconds(e),i=v.length?v[v.length-1]:0;p.appendInterval(t,i);const r=J.get(ct.eventStyle(e).category);0!==r&&v.push(void 0!==r?r:m)}),(function(e){const{endTime:t}=n.TracingModel.timesForEventInMilliseconds(e),i=v.pop();void 0!==t&&i&&p.appendInterval(t,i)})),p.appendInterval(o+l+d,0);for(let t=h.length-1;t>0;--t)T[t].lineTo(i,a),e.fillStyle=c[h[t]].color,e.fill(T[t])}!function(e){const t=4*window.devicePixelRatio;e.save(),e.lineWidth=t/Math.sqrt(8);for(let n=.5;n<i+a;n+=t)e.moveTo(n,0),e.lineTo(n-a,a);e.globalCompositeOperation="destination-out",e.stroke(),e.restore()}(u)}}class X extends j{constructor(){super("responsiveness",null)}update(){if(super.update(),!this.model)return;const e=this.height(),t=this.model.timelineModel().minimumRecordTime(),i=this.model.timelineModel().maximumRecordTime()-t,n=this.width()/i,a=this.model.frames(),s=this.context(),o=new Path2D,l=new Path2D;for(let e=0;e<a.length;++e){const t=a[e];t.hasWarnings()&&d(t.startTime,t.duration)}for(const e of this.model.timelineModel().tracks()){const t=e.events;for(let e=0;e<t.length;++e){if(!r.TimelineModel.EventOnTimelineData.forEvent(t[e]).warning)continue;const i=t[e].duration;void 0!==i&&d(t[e].startTime,i)}}function d(i,r){const a=Math.round(n*(i-t)),s=Math.round(n*r);o.rect(a,0,s,e),l.moveTo(a+s,0),l.lineTo(a+s,e)}s.fillStyle="hsl(0, 80%, 90%)",s.strokeStyle="red",s.lineWidth=2*window.devicePixelRatio,s.fill(o),s.stroke(l)}}class Y extends j{frameToImagePromise;lastFrame;lastElement;drawGeneration;emptyImage;imageWidth;#e=null;constructor(e){super("filmstrip",null),this.frameToImagePromise=new Map,this.#e=e,this.lastFrame=null,this.lastElement=null,this.reset()}update(){super.update();const e=this.#e?this.#e.frames():[];if(!e.length)return;const t=Symbol("drawGeneration");this.drawGeneration=t,this.imageByFrame(e[0]).then((e=>{if(this.drawGeneration!==t)return;if(!e||!e.naturalWidth||!e.naturalHeight)return;const i=this.height()-2*Y.Padding,n=Math.ceil(i*e.naturalWidth/e.naturalHeight),r=Math.min(200/e.naturalWidth,1);this.emptyImage=new Image(e.naturalWidth*r,e.naturalHeight*r),this.drawFrames(n,i)}))}async imageByFrame(e){let t=this.frameToImagePromise.get(e);if(!t){const i=await e.imageDataPromise();t=c.UIUtils.loadImageFromData(i),this.frameToImagePromise.set(e,t)}return t}drawFrames(e,t){if(!e||!this.model)return;if(!this.#e||this.#e.frames().length<1)return;const i=Y.Padding,n=this.width(),r=this.#e.zeroTime(),a=this.#e.spanTime()/n,s=this.context(),o=this.drawGeneration;s.beginPath();for(let o=i;o<n;o+=e+2*i){const i=r+(o+e/2)*a,n=this.#e.frameByTimestamp(i);n&&(s.rect(o-.5,.5,e+1,t+1),this.imageByFrame(n).then(l.bind(this,o)))}function l(i,n){this.drawGeneration===o&&n&&s.drawImage(n,i,1,e,t)}s.strokeStyle="#ddd",s.stroke()}async overviewInfoPromise(e){if(!this.#e||0===this.#e.frames().length)return null;const t=this.calculator();if(!t)return null;const i=t.positionToTime(e),n=this.#e.frameByTimestamp(i);if(n===this.lastFrame)return this.lastElement;const r=n?this.imageByFrame(n):Promise.resolve(this.emptyImage),a=await r,s=document.createElement("div");return s.classList.add("frame"),a&&s.createChild("div","thumbnail").appendChild(a),this.lastFrame=n,this.lastElement=s,s}reset(){this.lastFrame=null,this.lastElement=null,this.frameToImagePromise=new Map,this.imageWidth=0}static Padding=2}class K extends j{heapSizeLabel;constructor(){super("memory",_(z.heap)),this.heapSizeLabel=this.element.createChild("div","memory-graph-label")}resetHeapSizeLabels(){this.heapSizeLabel.textContent=""}update(){super.update();const e=window.devicePixelRatio;if(!this.model)return void this.resetHeapSizeLabels();const t=this.model.timelineModel().tracks().filter((e=>e.type===r.TimelineModel.TrackType.MainThread&&e.forMainFrame)).map((e=>e.events)),i=3*e;let n=0,a=1e11;const o=this.model.timelineModel().minimumRecordTime(),l=this.model.timelineModel().maximumRecordTime();function d(e){return e.name===r.TimelineModel.RecordType.UpdateCounters}for(let e=0;e<t.length;e++)t[e]=t[e].filter(d);function c(e){const t=e.args.data;t&&t.jsHeapSizeUsed&&(n=Math.max(n,t.jsHeapSizeUsed),a=Math.min(a,t.jsHeapSizeUsed))}for(let e=0;e<t.length;e++)t[e].forEach(c);a=Math.min(a,n);const h=this.width(),m=this.height()-i,u=h/(l-o),p=(m-1)/Math.max(n-a,1),g=new Array(h);function v(e){const t=e.args.data;if(!t||!t.jsHeapSizeUsed)return;const i=Math.round((e.startTime-o)*u),n=Math.round((t.jsHeapSizeUsed-a)*p);g[i]=Math.max(g[i]||0,n)}for(let e=0;e<t.length;e++)t[e].forEach(v);const T=this.context(),f=m+i+1;T.translate(.5,.5),T.beginPath(),T.moveTo(-1,f);let w=0,y=!0,S=0;for(let e=0;e<g.length;e++){if(void 0===g[e])continue;y&&(y=!1,w=g[e],T.lineTo(-1,m-w));const t=g[e];Math.abs(t-w)>2&&Math.abs(e-S)>1&&T.lineTo(e,m-w),w=t,T.lineTo(e,m-w),S=e}T.lineTo(h+1,m-w),T.lineTo(h+1,f),T.closePath(),T.fillStyle="hsla(220, 90%, 70%, 0.2)",T.fill(),T.lineWidth=1,T.strokeStyle="hsl(220, 90%, 70%)",T.stroke(),this.heapSizeLabel.textContent=_(z.sSDash,{PH1:s.NumberUtilities.bytesToString(a),PH2:s.NumberUtilities.bytesToString(n)})}}class Z{lastTime;quantDuration;callback;counters;remainder;constructor(e,t,i){this.lastTime=e,this.quantDuration=t,this.callback=i,this.counters=[],this.remainder=t}appendInterval(e,t){let i=e-this.lastTime;if(i<=this.remainder)return this.counters[t]=(this.counters[t]||0)+i,this.remainder-=i,void(this.lastTime=e);for(this.counters[t]=(this.counters[t]||0)+this.remainder,this.callback(this.counters),i-=this.remainder;i>=this.quantDuration;){const e=[];e[t]=this.quantDuration,this.callback(e),i-=this.quantDuration}this.counters=[],this.counters[t]=i,this.lastTime=e,this.remainder=this.quantDuration-i}}var Q=Object.freeze({__proto__:null,TimelineEventOverview:j,TimelineEventOverviewNetwork:q,TimelineEventOverviewCPUActivity:$,TimelineEventOverviewResponsiveness:X,TimelineFilmStripOverview:Y,TimelineEventOverviewMemory:K,Quantizer:Z});const ee=new CSSStyleSheet;ee.replaceSync(".drop-down{padding:1px;box-shadow:var(--drop-shadow);background:var(--color-background)}.preview-item{border-color:transparent;border-style:solid;border-width:1px 5px;padding:2px 0;margin:2px 1px}.preview-item.selected{border-color:var(--legacy-selection-bg-color)}.preview-item canvas{width:100%;height:100%}.text-details{font-size:11px;padding:3px}.text-details span{flex:1 0;padding-left:8px;padding-right:8px}.text-details .name{font-weight:bold}.text-details span.time{color:var(--color-text-secondary);text-align:right}.screenshot-thumb{display:flex;border:1px solid var(--color-background-elevation-2);margin:2px 4px}.screenshot-thumb img{margin:auto;max-width:100%;max-height:100%}\n/*# sourceURL=timelineHistoryManager.css */\n");const te={currentSessionSS:"Current Session: {PH1}. {PH2}",noRecordings:"(no recordings)",sAgo:"({PH1} ago)",moments:"moments",sM:"{PH1} m",sH:"{PH1} h",sD:"{PH1} #{PH2}",selectTimelineSession:"Select Timeline Session"},ie=i.i18n.registerUIStrings("panels/timeline/TimelineHistoryManager.ts",te),ne=i.i18n.getLocalizedString.bind(void 0,ie);class re{recordings;action;nextNumberByDomain;buttonInternal;allOverviews;totalHeight;enabled;lastActiveModel;constructor(){this.recordings=[],this.action=c.ActionRegistry.ActionRegistry.instance().action("timeline.show-history"),this.nextNumberByDomain=new Map,this.buttonInternal=new de(this.action),c.ARIAUtils.markAsMenuButton(this.buttonInternal.element),this.clear(),this.allOverviews=[{constructor:X,height:3},{constructor:$,height:20},{constructor:q,height:8}],this.totalHeight=this.allOverviews.reduce(((e,t)=>e+t.height),0),this.enabled=!0,this.lastActiveModel=null}addRecording(e,t,i){this.lastActiveModel=e,this.recordings.unshift({legacyModel:e,traceParseData:t,filmStripModel:i}),this.buildPreview(e,i);const n=this.title(e);this.buttonInternal.setText(n);const r=this.action.title();if(c.ARIAUtils.setLabel(this.buttonInternal.element,ne(te.currentSessionSS,{PH1:n,PH2:r})),this.updateState(),this.recordings.length<=ae)return;const a=this.recordings.reduce(((e,t)=>s(e.legacyModel)<s(t.legacyModel)?e:t));function s(e){const t=re.dataForModel(e);if(!t)throw new Error("Unable to find data for model");return t.lastUsed}this.recordings.splice(this.recordings.indexOf(a),1)}setEnabled(e){this.enabled=e,this.updateState()}button(){return this.buttonInternal}clear(){this.recordings=[],this.lastActiveModel=null,this.updateState(),this.buttonInternal.setText(ne(te.noRecordings)),this.nextNumberByDomain.clear()}async showHistoryDropDown(){if(this.recordings.length<2||!this.enabled)return null;const e=await le.show(this.recordings.map((e=>e.legacyModel)),this.lastActiveModel,this.buttonInternal.element);if(!e)return null;const t=this.recordings.findIndex((t=>t.legacyModel===e));return t<0?(console.assert(!1,"selected recording not found"),null):(this.setCurrentModel(e),this.recordings[t])}cancelIfShowing(){le.cancelIfShowing()}navigate(e){if(!this.enabled||!this.lastActiveModel)return null;const t=this.recordings.findIndex((e=>e.legacyModel===this.lastActiveModel));if(t<0)return null;const i=s.NumberUtilities.clamp(t+e,0,this.recordings.length-1),n=this.recordings[i].legacyModel;return this.setCurrentModel(n),this.recordings[i]}setCurrentModel(e){const t=re.dataForModel(e);if(!t)throw new Error("Unable to find data for model");t.lastUsed=Date.now(),this.lastActiveModel=e;const i=this.title(e),n=this.action.title();this.buttonInternal.setText(i),c.ARIAUtils.setLabel(this.buttonInternal.element,ne(te.currentSessionSS,{PH1:i,PH2:n}))}updateState(){this.action.setEnabled(this.recordings.length>1&&this.enabled)}static previewElement(e){const t=re.dataForModel(e);if(!t)throw new Error("Unable to find data for model");const i=e.recordStartTime();return t.time.textContent=i?ne(te.sAgo,{PH1:re.coarseAge(i)}):"",t.preview}static coarseAge(e){const t=Math.round((Date.now()-e)/1e3);if(t<50)return ne(te.moments);const i=Math.round(t/60);if(i<50)return ne(te.sM,{PH1:i});const n=Math.round(i/60);return ne(te.sH,{PH1:n})}title(e){const t=re.dataForModel(e);if(!t)throw new Error("Unable to find data for model");return t.title}buildPreview(e,t){const i=a.ParsedURL.ParsedURL.fromString(e.timelineModel().pageURL()),n=i?i.host:"",r=e.tracingModel().title()||n,s=this.nextNumberByDomain.get(r)||1,o=ne(te.sD,{PH1:r,PH2:s});this.nextNumberByDomain.set(r,s+1);const l=document.createElement("span"),d=document.createElement("div");d.classList.add("preview-item"),d.classList.add("vbox");const c={preview:d,title:o,time:l,lastUsed:Date.now()};oe.set(e,c),d.appendChild(this.buildTextDetails(e,r,l));const h=d.createChild("div","hbox");return h.appendChild(this.buildScreenshotThumbnail(t)),h.appendChild(this.buildOverview(e)),c.preview}buildTextDetails(e,t,n){const r=document.createElement("div");r.classList.add("text-details"),r.classList.add("hbox");const a=r.createChild("span","name");a.textContent=t,c.ARIAUtils.setLabel(a,t);const s=e.tracingModel(),o=i.TimeUtilities.millisToString(s.maximumRecordTime()-s.minimumRecordTime(),!1),l=r.createChild("span","time");return l.appendChild(document.createTextNode(o)),l.appendChild(n),r}buildScreenshotThumbnail(e){const t=document.createElement("div");t.classList.add("screenshot-thumb");t.style.width=1.5*this.totalHeight+"px",t.style.height=this.totalHeight+"px";const i=e.frames(),n=i[i.length-1];return n?(n.imageDataPromise().then((e=>c.UIUtils.loadImageFromData(e))).then((e=>e&&t.appendChild(e))),t):t}buildOverview(e){const t=document.createElement("div");t.style.width=se+"px",t.style.height=this.totalHeight+"px";const i=t.createChild("canvas");i.width=window.devicePixelRatio*se,i.height=window.devicePixelRatio*this.totalHeight;const n=i.getContext("2d");let r=0;for(const t of this.allOverviews){const i=new t.constructor;i.setCanvasSize(se,t.height),i.setModel(e),i.update();const a=i.context(),s=a.getImageData(0,0,a.canvas.width,a.canvas.height);n&&n.putImageData(s,0,r),r+=t.height*window.devicePixelRatio}return t}static dataForModel(e){return oe.get(e)||null}}const ae=5,se=450,oe=new WeakMap;class le{glassPane;listControl;focusRestorer;selectionDone;constructor(e){this.glassPane=new c.GlassPane.GlassPane,this.glassPane.setSizeBehavior("MeasureContent"),this.glassPane.setOutsideClickCallback((()=>this.close(null))),this.glassPane.setPointerEventsBehavior("BlockedByGlassPane"),this.glassPane.setAnchorBehavior("PreferBottom"),this.glassPane.element.addEventListener("blur",(()=>this.close(null)));const t=c.Utils.createShadowRootWithCoreStyles(this.glassPane.contentElement,{cssFile:[ee],delegatesFocus:void 0}).createChild("div","drop-down"),i=new c.ListModel.ListModel;this.listControl=new c.ListControl.ListControl(i,this,c.ListControl.ListMode.NonViewport),this.listControl.element.addEventListener("mousemove",this.onMouseMove.bind(this),!1),i.replaceAll(e),c.ARIAUtils.markAsMenu(this.listControl.element),c.ARIAUtils.setLabel(this.listControl.element,ne(te.selectTimelineSession)),t.appendChild(this.listControl.element),t.addEventListener("keydown",this.onKeyDown.bind(this),!1),t.addEventListener("click",this.onClick.bind(this),!1),this.focusRestorer=new c.UIUtils.ElementFocusRestorer(this.listControl.element),this.selectionDone=null}static show(e,t,i){if(le.instance)return Promise.resolve(null);return new le(e).show(i,t)}static cancelIfShowing(){le.instance&&le.instance.close(null)}show(e,t){return le.instance=this,this.glassPane.setContentAnchorBox(e.boxInWindow()),this.glassPane.show(this.glassPane.contentElement.ownerDocument),this.listControl.element.focus(),this.listControl.selectItem(t),new Promise((e=>{this.selectionDone=e}))}onMouseMove(e){const t=e.target.enclosingNodeOrSelfWithClass("preview-item"),i=t&&this.listControl.itemForNode(t);i&&this.listControl.selectItem(i)}onClick(e){e.target.enclosingNodeOrSelfWithClass("preview-item")&&this.close(this.listControl.selectedItem())}onKeyDown(e){switch(e.key){case"Tab":case"Escape":this.close(null);break;case"Enter":this.close(this.listControl.selectedItem());break;default:return}e.consume(!0)}close(e){this.selectionDone&&this.selectionDone(e),this.focusRestorer.restore(),this.glassPane.hide(),le.instance=null}createElementForItem(e){const t=re.previewElement(e);return c.ARIAUtils.markAsMenuItem(t),t.classList.remove("selected"),t}heightForItem(e){return console.assert(!1,"Should not be called"),0}isItemSelectable(e){return!0}selectedItemChanged(e,t,i,n){i&&i.classList.remove("selected"),n&&n.classList.add("selected")}updateSelectedItemARIA(e,t){return!1}static instance=null}class de extends c.Toolbar.ToolbarItem{contentElement;constructor(e){const t=document.createElement("button");t.classList.add("history-dropdown-button"),super(t),this.contentElement=this.element.createChild("span","content");const i=c.Icon.Icon.create("triangle-down");this.element.appendChild(i),this.element.addEventListener("click",(()=>{e.execute()}),!1),this.setEnabled(e.enabled()),e.addEventListener("Enabled",(e=>this.setEnabled(e.data))),this.setTitle(e.title())}setText(e){this.contentElement.textContent=e}}var ce=Object.freeze({__proto__:null,TimelineHistoryManager:re,maxRecordings:ae,previewWidth:se,DropDown:le,ToolbarButton:de});const he={malformedTimelineDataUnknownJson:"Malformed timeline data: Unknown JSON format",malformedTimelineInputWrongJson:"Malformed timeline input, wrong JSON brackets balance",malformedTimelineDataS:"Malformed timeline data: {PH1}",legacyTimelineFormatIsNot:"Legacy Timeline format is not supported.",malformedCpuProfileFormat:"Malformed CPU profile format"},me=i.i18n.registerUIStrings("panels/timeline/TimelineLoader.ts",he),ue=i.i18n.getLocalizedString.bind(void 0,me);class pe{client;tracingModel;canceledCallback;state;buffer;firstRawChunk;firstChunk;loadedBytes;totalSize;jsonTokenizer;filter;constructor(e,t){this.client=e,this.tracingModel=new n.TracingModel.TracingModel(t),this.canceledCallback=null,this.state=ve.Initial,this.buffer="",this.firstRawChunk=!0,this.firstChunk=!0,this.loadedBytes=0,this.jsonTokenizer=new v.TextUtils.BalancedJSONTokenizer(this.writeBalancedJSON.bind(this),!0),this.filter=null}static async loadFromFile(e,t){const i=new pe(t),n=new l.FileUtils.ChunkedFileReader(e,ge);i.canceledCallback=n.cancel.bind(n),i.totalSize=e.size;return!await n.read(i)&&n.error()&&i.reportErrorAndCancelLoading(n.error().message),i}static loadFromEvents(e,t){const i=new pe(t);return window.setTimeout((async()=>{i.addEvents(e)})),i}static getCpuProfileFilter(){const e=[];return e.push(r.TimelineModel.RecordType.JSFrame),e.push(r.TimelineModel.RecordType.JSIdleFrame),e.push(r.TimelineModel.RecordType.JSSystemFrame),new r.TimelineModelFilter.TimelineVisibleEventsFilter(e)}static loadFromCpuProfile(e,t,i){const n=new pe(t,i);try{const t=r.TimelineJSProfile.TimelineJSProfileProcessor.createFakeTraceFromCpuProfile(e,1,!0);n.filter=pe.getCpuProfileFilter(),window.setTimeout((async()=>{n.addEvents(t)}))}catch(e){console.error(e.stack)}return n}static async loadFromURL(e,t){const i=new pe(t),n=new a.StringOutputStream.StringOutputStream;await t.loadingStarted();const r=a.Settings.Settings.instance().moduleSetting("network.enable-remote-file-loading").get();return u.ResourceLoader.loadAsStream(e,null,n,(async function(e,t,r){if(!e)return i.reportErrorAndCancelLoading(r.message);const a=n.data(),s=JSON.parse(a);if(Array.isArray(s.nodes))return i.state=ve.LoadingCPUProfileFormat,i.buffer=a,void await i.close();const o=Array.isArray(s.traceEvents)?s.traceEvents:s;i.addEvents(o)}),r),i}async addEvents(e){await(this.client?.loadingStarted());for(let t=0;t<e.length;t+=15e3){const i=e.slice(t,t+15e3);this.tracingModel.addEvents(i),await(this.client?.loadingProgress((t+i.length)/e.length)),await new Promise((e=>window.setTimeout(e)))}this.close()}async cancel(){this.tracingModel=null,this.client&&(await this.client.loadingComplete(null,null),this.client=null),this.canceledCallback&&this.canceledCallback()}async write(e){if(!this.client)return Promise.resolve();if(this.loadedBytes+=e.length,this.firstRawChunk)await this.client.loadingStarted(),await new Promise((e=>requestAnimationFrame((()=>requestAnimationFrame(e)))));else{let e;this.totalSize&&(e=this.loadedBytes/this.totalSize,e=e>1?e-Math.floor(e):e),await this.client.loadingProgress(e)}if(this.firstRawChunk=!1,this.state===ve.Initial)if(e.match(/^{(\s)*"nodes":(\s)*\[/))this.state=ve.LoadingCPUProfileFormat;else if("{"===e[0])this.state=ve.LookingForEvents;else{if("["!==e[0])return this.reportErrorAndCancelLoading(ue(he.malformedTimelineDataUnknownJson)),Promise.resolve();this.state=ve.ReadingEvents}if(this.state===ve.LoadingCPUProfileFormat)return this.buffer+=e,Promise.resolve();if(this.state===ve.LookingForEvents){const t='"traceEvents":',i=this.buffer.length-t.length;this.buffer+=e;const n=this.buffer.indexOf(t,i);if(-1===n)return Promise.resolve();e=this.buffer.slice(n+t.length),this.state=ve.ReadingEvents}return this.state!==ve.ReadingEvents||this.jsonTokenizer.write(e)||(this.state=ve.SkippingTail,this.firstChunk&&this.reportErrorAndCancelLoading(ue(he.malformedTimelineInputWrongJson))),Promise.resolve()}writeBalancedJSON(e){let t,i=e+"]";if(!this.firstChunk){const e=i.indexOf(",");-1!==e&&(i=i.slice(e+1)),i="["+i}try{t=JSON.parse(i)}catch(e){return void this.reportErrorAndCancelLoading(ue(he.malformedTimelineDataS,{PH1:e.toString()}))}if(this.firstChunk&&(this.firstChunk=!1,this.looksLikeAppVersion(t[0])))this.reportErrorAndCancelLoading(ue(he.legacyTimelineFormatIsNot));else try{this.tracingModel.addEvents(t)}catch(e){this.reportErrorAndCancelLoading(ue(he.malformedTimelineDataS,{PH1:e.toString()}))}}reportErrorAndCancelLoading(e){e&&a.Console.Console.instance().error(e),this.cancel()}looksLikeAppVersion(e){return"string"==typeof e&&-1!==e.indexOf("Chrome")}async close(){this.client&&(await this.client.processingStarted(),await this.finalizeTrace())}async finalizeTrace(){this.state===ve.LoadingCPUProfileFormat&&(this.parseCPUProfileFormat(this.buffer),this.buffer=""),this.tracingModel.tracingComplete(),await this.client.loadingComplete(this.tracingModel,this.filter)}parseCPUProfileFormat(e){let t;try{const i=JSON.parse(e);t=r.TimelineJSProfile.TimelineJSProfileProcessor.createFakeTraceFromCpuProfile(i,1,!0)}catch(e){return void this.reportErrorAndCancelLoading(ue(he.malformedCpuProfileFormat))}this.filter=pe.getCpuProfileFilter(),this.tracingModel.addEvents(t)}}const ge=5e6;var ve;!function(e){e.Initial="Initial",e.LookingForEvents="LookingForEvents",e.ReadingEvents="ReadingEvents",e.SkippingTail="SkippingTail",e.LoadingCPUProfileFormat="LoadingCPUProfileFormat"}(ve||(ve={}));var Te=Object.freeze({__proto__:null,TimelineLoader:pe,TransferChunkLengthBytes:ge,get State(){return ve}});const fe={frameStart:"Frame Start",drawFrame:"Draw Frame",layout:"Layout",rasterizing:"Rasterizing",drawing:"Drawing",painting:"Painting",system:"System",idle:"Idle"},we=i.i18n.registerUIStrings("panels/timeline/UIDevtoolsUtils.ts",fe),ye=i.i18n.getLocalizedString.bind(void 0,we);let Se=null,be=null;class Ce{static isUiDevTools(){return"true"===o.Runtime.Runtime.queryParam("uiDevTools")}static categorizeEvents(){if(Se)return Se;const e=ke,t=Ce.categories(),i=t.drawing,n=t.rasterizing,r=t.layout,a=t.painting,s=t.other,o={};return o[e.ViewPaint]=new ht("View::Paint",a),o[e.ViewOnPaint]=new ht("View::OnPaint",a),o[e.ViewPaintChildren]=new ht("View::PaintChildren",a),o[e.ViewOnPaintBackground]=new ht("View::OnPaintBackground",a),o[e.ViewOnPaintBorder]=new ht("View::OnPaintBorder",a),o[e.LayerPaintContentsToDisplayList]=new ht("Layer::PaintContentsToDisplayList",a),o[e.ViewLayout]=new ht("View::Layout",r),o[e.ViewLayoutBoundsChanged]=new ht("View::Layout(bounds_changed)",r),o[e.RasterTask]=new ht("RasterTask",n),o[e.RasterizerTaskImplRunOnWorkerThread]=new ht("RasterizerTaskImpl::RunOnWorkerThread",n),o[e.DirectRendererDrawFrame]=new ht("DirectRenderer::DrawFrame",i),o[e.BeginFrame]=new ht(ye(fe.frameStart),i,!0),o[e.DrawFrame]=new ht(ye(fe.drawFrame),i,!0),o[e.NeedsBeginFrameChanged]=new ht("NeedsBeginFrameChanged",i,!0),o[e.ThreadControllerImplRunTask]=new ht("ThreadControllerImpl::RunTask",s),Se=o,o}static categories(){return be||(be={layout:new Tt("layout",ye(fe.layout),!0,"hsl(214, 67%, 74%)","hsl(214, 67%, 66%)"),rasterizing:new Tt("rasterizing",ye(fe.rasterizing),!0,"hsl(43, 83%, 72%)","hsl(43, 83%, 64%) "),drawing:new Tt("drawing",ye(fe.drawing),!0,"hsl(256, 67%, 76%)","hsl(256, 67%, 70%)"),painting:new Tt("painting",ye(fe.painting),!0,"hsl(109, 33%, 64%)","hsl(109, 33%, 55%)"),other:new Tt("other",ye(fe.system),!1,"hsl(0, 0%, 87%)","hsl(0, 0%, 79%)"),idle:new Tt("idle",ye(fe.idle),!1,"hsl(0, 0%, 98%)","hsl(0, 0%, 98%)")},be)}static getMainCategoriesList(){return["idle","drawing","painting","rasterizing","layout","other"]}}var ke;!function(e){e.ViewPaint="View::Paint",e.ViewOnPaint="View::OnPaint",e.ViewPaintChildren="View::PaintChildren",e.ViewOnPaintBackground="View::OnPaintBackground",e.ViewOnPaintBorder="View::OnPaintBorder",e.ViewLayout="View::Layout",e.ViewLayoutBoundsChanged="View::Layout(bounds_changed)",e.LayerPaintContentsToDisplayList="Layer::PaintContentsToDisplayList",e.DirectRendererDrawFrame="DirectRenderer::DrawFrame",e.RasterTask="RasterTask",e.RasterizerTaskImplRunOnWorkerThread="RasterizerTaskImpl::RunOnWorkerThread",e.BeginFrame="BeginFrame",e.DrawFrame="DrawFrame",e.NeedsBeginFrameChanged="NeedsBeginFrameChanged",e.ThreadControllerImplRunTask="ThreadControllerImpl::RunTask"}(ke||(ke={}));var Pe=Object.freeze({__proto__:null,UIDevtoolsUtils:Ce,get RecordType(){return ke}});class Me extends V{constructor(e,t){super(e,t),ct.setEventStylesMap(Ce.categorizeEvents()),ct.setCategories(Ce.categories()),ct.setTimelineMainEventCategories(Ce.getMainCategoriesList())}}var Ee=Object.freeze({__proto__:null,UIDevtoolsController:Me});function*xe(e){if(yield"[\n",e.length>0){const t=e[Symbol.iterator](),i=t.next().value;yield`  ${JSON.stringify(i)}`;let n=1e4,r="";for(const e of t)r+=`,\n  ${JSON.stringify(e)}`,n--,0===n&&(yield r,n=1e4,r="");yield r}yield"\n]"}function*Ie(e,t){yield'{"traceEvents": ',yield*xe(e),yield`,\n"metadata": ${JSON.stringify(t||{},null,2)}`,yield"}\n"}function Le(e){return JSON.stringify(e)}var Re=Object.freeze({__proto__:null,arrayOfObjectsJsonGenerator:xe,traceJsonGenerator:Ie,cpuprofileJsonGenerator:Le});const Fe=Symbol("SelectionRange");class De{startTime;endTime;object;constructor(e,t,i){this.startTime=e,this.endTime=t,this.object=i}static isFrameObject(e){return e instanceof r.TimelineFrameModel.TimelineFrame}static fromFrame(t){return new De(e.Types.Timing.MilliSeconds(t.startTime),e.Types.Timing.MilliSeconds(t.endTime),t)}static isNetworkRequestSelection(e){return e instanceof r.TimelineModel.NetworkRequest}static fromNetworkRequest(t){return new De(e.Types.Timing.MilliSeconds(t.startTime),e.Types.Timing.MilliSeconds(t.endTime||t.startTime),t)}static isTraceEventSelection(e){return e instanceof n.TracingModel.Event||!(De.isFrameObject(e)||De.isRangeSelection(e)||De.isNetworkRequestSelection(e))&&n.TracingModel.eventIsFromNewEngine(e)}static fromTraceEvent(t){const{startTime:i,endTime:r}=n.TracingModel.timesForEventInMilliseconds(t);return new De(i,e.Types.Timing.MilliSeconds(r||i+1),t)}static isRangeSelection(e){return e===Fe}static fromRange(t,i){return new De(e.Types.Timing.MilliSeconds(t),e.Types.Timing.MilliSeconds(i),Fe)}}var Ue=Object.freeze({__proto__:null,TimelineSelection:De});const He={dropTimelineFileOrUrlHere:"Drop timeline file or URL here",disableJavascriptSamples:"Disable JavaScript samples",enableAdvancedPaint:"Enable advanced paint instrumentation (slow)",screenshots:"Screenshots",memory:"Memory",clear:"Clear",loadProfile:"Load profile…",saveProfile:"Save profile…",captureScreenshots:"Capture screenshots",showMemoryTimeline:"Show memory timeline",captureSettings:"Capture settings",disablesJavascriptSampling:"Disables JavaScript sampling, reduces overhead when running against mobile devices",capturesAdvancedPaint:"Captures advanced paint instrumentation, introduces significant performance overhead",network:"Network:",cpu:"CPU:",networkConditions:"Network conditions",failedToSaveTimelineSS:"Failed to save timeline: {PH1} ({PH2})",CpuThrottlingIsEnabled:"- CPU throttling is enabled",NetworkThrottlingIsEnabled:"- Network throttling is enabled",HardwareConcurrencyIsEnabled:"- Hardware concurrency override is enabled",SignificantOverheadDueToPaint:"- Significant overhead due to paint instrumentation",JavascriptSamplingIsDisabled:"- JavaScript sampling is disabled",stoppingTimeline:"Stopping timeline…",received:"Received",close:"Close",recordingFailed:"Recording failed",profiling:"Profiling…",bufferUsage:"Buffer usage",learnmore:"Learn more",wasd:"WASD",clickTheRecordButtonSOrHitSTo:"Click the record button {PH1} or hit {PH2} to start a new recording.",clickTheReloadButtonSOrHitSTo:"Click the reload button {PH1} or hit {PH2} to record the page load.",afterRecordingSelectAnAreaOf:"After recording, select an area of interest in the overview by dragging. Then, zoom and pan the timeline with the mousewheel or {PH1} keys. {PH2}",loadingProfile:"Loading profile…",processingProfile:"Processing profile…",initializingProfiler:"Initializing profiler…",status:"Status",time:"Time",description:"Description",stop:"Stop",ssec:"{PH1} sec",couldNotStart:"Could not start recording, please try again later"},Ne=i.i18n.registerUIStrings("panels/timeline/TimelinePanel.ts",He),Ae=i.i18n.getLocalizedString.bind(void 0,Ne);let Be,We;class Ve extends c.Panel.Panel{dropTarget;recordingOptionUIControls;state;recordingPageReload;millisecondsToRecordAfterLoadEvent;toggleRecordAction;recordReloadAction;historyManager;performanceModel;filmStripModel=null;disableCaptureJSProfileSetting;captureLayersAndPicturesSetting;showScreenshotsSetting;showMemorySetting;panelToolbar;panelRightToolbar;timelinePane;overviewPane;overviewControls;statusPaneContainer;flameChart;searchableViewInternal;showSettingsPaneButton;showSettingsPaneSetting;settingsPane;controller;cpuProfiler;clearButton;loadButton;saveButton;statusPane;landingPage;loader;showScreenshotsToolbarCheckbox;showMemoryToolbarCheckbox;networkThrottlingSelect;cpuThrottlingSelect;fileSelectorElement;selection;primaryPageTargetPromiseCallback=e=>{};primaryPageTargetPromise=new Promise((e=>{this.primaryPageTargetPromiseCallback=e}));#t;#i=-1;constructor(){super("timeline"),this.#t=e.TraceModel.Model.createWithRequiredHandlersForMigration(),this.element.addEventListener("contextmenu",this.contextMenu.bind(this),!1),this.dropTarget=new c.DropTarget.DropTarget(this.element,[c.DropTarget.Type.File,c.DropTarget.Type.URI],Ae(He.dropTimelineFileOrUrlHere),this.handleDrop.bind(this)),this.recordingOptionUIControls=[],this.state=Oe.Idle,this.recordingPageReload=!1,this.millisecondsToRecordAfterLoadEvent=5e3,this.toggleRecordAction=c.ActionRegistry.ActionRegistry.instance().action("timeline.toggle-recording"),this.recordReloadAction=c.ActionRegistry.ActionRegistry.instance().action("timeline.record-reload"),this.historyManager=new re,this.performanceModel=null,this.disableCaptureJSProfileSetting=a.Settings.Settings.instance().createSetting("timelineDisableJSSampling",!1),this.disableCaptureJSProfileSetting.setTitle(Ae(He.disableJavascriptSamples)),this.captureLayersAndPicturesSetting=a.Settings.Settings.instance().createSetting("timelineCaptureLayersAndPictures",!1),this.captureLayersAndPicturesSetting.setTitle(Ae(He.enableAdvancedPaint)),this.showScreenshotsSetting=a.Settings.Settings.instance().createSetting("timelineShowScreenshots",!We),this.showScreenshotsSetting.setTitle(Ae(He.screenshots)),this.showScreenshotsSetting.addChangeListener(this.updateOverviewControls,this),this.showMemorySetting=a.Settings.Settings.instance().createSetting("timelineShowMemory",!1),this.showMemorySetting.setTitle(Ae(He.memory)),this.showMemorySetting.addChangeListener(this.onModeChanged,this);const t=this.element.createChild("div","timeline-toolbar-container");this.panelToolbar=new c.Toolbar.Toolbar("timeline-main-toolbar",t),this.panelToolbar.makeWrappable(!0),this.panelRightToolbar=new c.Toolbar.Toolbar("",t),We||(this.createSettingsPane(),this.updateShowSettingsToolbarButton()),this.timelinePane=new c.Widget.VBox,this.timelinePane.show(this.element);const i=this.timelinePane.element.createChild("div","hbox");if(i.id="timeline-overview-panel",this.overviewPane=new d.TimelineOverviewPane.TimelineOverviewPane("timeline"),this.overviewPane.addEventListener(d.TimelineOverviewPane.Events.WindowChanged,this.onOverviewWindowChanged.bind(this)),this.overviewPane.show(i),this.overviewControls=[],this.statusPaneContainer=this.timelinePane.element.createChild("div","status-pane-container fill"),this.createFileSelector(),n.TargetManager.TargetManager.instance().addModelListener(n.ResourceTreeModel.ResourceTreeModel,n.ResourceTreeModel.Events.Load,this.loadEventFired,this),this.flameChart=new Si(this),this.searchableViewInternal=new c.SearchableView.SearchableView(this.flameChart,null),this.searchableViewInternal.setMinimumSize(0,100),this.searchableViewInternal.element.classList.add("searchable-view"),this.searchableViewInternal.show(this.timelinePane.element),this.flameChart.show(this.searchableViewInternal.element),this.flameChart.setSearchableView(this.searchableViewInternal),this.searchableViewInternal.hideWidget(),this.onModeChanged(),this.populateToolbar(),this.showLandingPage(),this.updateTimelineControls(),n.TargetManager.TargetManager.instance().addEventListener(n.TargetManager.Events.SuspendStateChanged,this.onSuspendStateChanged,this),o.Runtime.experiments.isEnabled("timelineAsConsoleProfileResultPanel")){const e=n.TargetManager.TargetManager.instance().models(n.CPUProfilerModel.CPUProfilerModel);for(const t of e)for(const e of t.registeredConsoleProfileMessages)this.consoleProfileFinished(e);n.TargetManager.TargetManager.instance().observeModels(n.CPUProfilerModel.CPUProfilerModel,{modelAdded:e=>{e.addEventListener(n.CPUProfilerModel.Events.ConsoleProfileFinished,(e=>this.consoleProfileFinished(e.data)))},modelRemoved:e=>{}})}n.TargetManager.TargetManager.instance().observeTargets({targetAdded:e=>{e===n.TargetManager.TargetManager.instance().primaryPageTarget()&&this.primaryPageTargetPromiseCallback(e)},targetRemoved:e=>{}})}static instance(e={forceNew:null,isNode:!1}){const{forceNew:t,isNode:i}=e;return We=i,Be&&!t||(Be=new Ve),Be}searchableView(){return this.searchableViewInternal}wasShown(){super.wasShown(),c.Context.Context.instance().setFlavor(Ve,this),this.registerCSSFiles([H]),u.userMetrics.panelLoaded("timeline","DevTools.Launch.Timeline")}willHide(){c.Context.Context.instance().setFlavor(Ve,null),this.historyManager.cancelIfShowing()}loadFromEvents(e){this.state===Oe.Idle&&(this.prepareToLoadTimeline(),this.loader=pe.loadFromEvents(e,this))}loadFromCpuProfile(e,t){this.state===Oe.Idle&&(this.prepareToLoadTimeline(),this.loader=pe.loadFromCpuProfile(e,this,t))}onOverviewWindowChanged(e){if(!this.performanceModel)return;const t=e.data.startTime,i=e.data.endTime;this.performanceModel.setWindow({left:t,right:i},!0)}onModelWindowChanged(e){const t=e.data.window;this.overviewPane.setWindowTimes(t.left,t.right)}setState(e){this.state=e,this.updateTimelineControls()}createSettingCheckbox(e,t){const i=new c.Toolbar.ToolbarSettingCheckbox(e,t);return this.recordingOptionUIControls.push(i),i}populateToolbar(){this.panelToolbar.appendToolbarItem(c.Toolbar.Toolbar.createActionButton(this.toggleRecordAction)),this.panelToolbar.appendToolbarItem(c.Toolbar.Toolbar.createActionButton(this.recordReloadAction)),this.clearButton=new c.Toolbar.ToolbarButton(Ae(He.clear),"clear"),this.clearButton.addEventListener(c.Toolbar.ToolbarButton.Events.Click,(()=>this.onClearButton())),this.panelToolbar.appendToolbarItem(this.clearButton),this.loadButton=new c.Toolbar.ToolbarButton(Ae(He.loadProfile),"import"),this.loadButton.addEventListener(c.Toolbar.ToolbarButton.Events.Click,(()=>{u.userMetrics.actionTaken(u.UserMetrics.Action.PerfPanelTraceImported),this.selectFileToLoad()})),this.saveButton=new c.Toolbar.ToolbarButton(Ae(He.saveProfile),"download"),this.saveButton.addEventListener(c.Toolbar.ToolbarButton.Events.Click,(e=>{u.userMetrics.actionTaken(u.UserMetrics.Action.PerfPanelTraceExported),this.saveToFile()})),this.panelToolbar.appendSeparator(),this.panelToolbar.appendToolbarItem(this.loadButton),this.panelToolbar.appendToolbarItem(this.saveButton),this.panelToolbar.appendSeparator(),this.panelToolbar.appendToolbarItem(this.historyManager.button()),this.panelToolbar.registerCSSFiles([U]),this.panelToolbar.appendSeparator(),this.panelToolbar.appendSeparator(),We||(this.showScreenshotsToolbarCheckbox=this.createSettingCheckbox(this.showScreenshotsSetting,Ae(He.captureScreenshots)),this.panelToolbar.appendToolbarItem(this.showScreenshotsToolbarCheckbox)),this.showMemoryToolbarCheckbox=this.createSettingCheckbox(this.showMemorySetting,Ae(He.showMemoryTimeline)),this.panelToolbar.appendToolbarItem(this.showMemoryToolbarCheckbox),this.panelToolbar.appendToolbarItem(c.Toolbar.Toolbar.createActionButtonForId("components.collect-garbage")),We||(this.panelRightToolbar.appendSeparator(),this.panelRightToolbar.appendToolbarItem(this.showSettingsPaneButton))}createSettingsPane(){this.showSettingsPaneSetting=a.Settings.Settings.instance().createSetting("timelineShowSettingsToolbar",!1),this.showSettingsPaneButton=new c.Toolbar.ToolbarSettingToggle(this.showSettingsPaneSetting,"gear",Ae(He.captureSettings),"gear-filled"),n.NetworkManager.MultitargetNetworkManager.instance().addEventListener(n.NetworkManager.MultitargetNetworkManager.Events.ConditionsChanged,this.updateShowSettingsToolbarButton,this),n.CPUThrottlingManager.CPUThrottlingManager.instance().addEventListener(n.CPUThrottlingManager.Events.RateChanged,this.updateShowSettingsToolbarButton,this),n.CPUThrottlingManager.CPUThrottlingManager.instance().addEventListener(n.CPUThrottlingManager.Events.HardwareConcurrencyChanged,this.updateShowSettingsToolbarButton,this),this.disableCaptureJSProfileSetting.addChangeListener(this.updateShowSettingsToolbarButton,this),this.captureLayersAndPicturesSetting.addChangeListener(this.updateShowSettingsToolbarButton,this),this.settingsPane=new c.Widget.HBox,this.settingsPane.element.classList.add("timeline-settings-pane"),this.settingsPane.show(this.element);const e=new c.Toolbar.Toolbar("",this.settingsPane.element);e.element.classList.add("flex-auto"),e.makeVertical(),e.appendToolbarItem(this.createSettingCheckbox(this.disableCaptureJSProfileSetting,Ae(He.disablesJavascriptSampling))),e.appendToolbarItem(this.createSettingCheckbox(this.captureLayersAndPicturesSetting,Ae(He.capturesAdvancedPaint)));const t=new c.Widget.VBox;t.element.classList.add("flex-auto"),t.show(this.settingsPane.element);const i=new c.Toolbar.Toolbar("",t.element);i.appendText(Ae(He.cpu)),this.cpuThrottlingSelect=g.ThrottlingManager.throttlingManager().createCPUThrottlingSelector(),i.appendToolbarItem(this.cpuThrottlingSelect);const r=new c.Toolbar.Toolbar("",t.element);r.appendText(Ae(He.network)),this.networkThrottlingSelect=this.createNetworkConditionsSelect(),r.appendToolbarItem(this.networkThrottlingSelect);const s=new c.Widget.VBox;s.element.classList.add("flex-auto"),s.show(this.settingsPane.element);const{toggle:o,input:l,reset:d,warning:h}=g.ThrottlingManager.throttlingManager().createHardwareConcurrencySelector(),m=new c.Toolbar.Toolbar("",s.element);m.registerCSSFiles([H]),l.element.classList.add("timeline-concurrency-input"),m.appendToolbarItem(o),m.appendToolbarItem(l),m.appendToolbarItem(d),m.appendToolbarItem(h),this.showSettingsPaneSetting.addChangeListener(this.updateSettingsPaneVisibility.bind(this)),this.updateSettingsPaneVisibility()}createNetworkConditionsSelect(){const e=new c.Toolbar.ToolbarComboBox(null,Ae(He.networkConditions));return e.setMaxWidth(140),g.ThrottlingManager.throttlingManager().decorateSelectWithNetworkThrottling(e.selectElement()),e}prepareToLoadTimeline(){console.assert(this.state===Oe.Idle),this.setState(Oe.Loading),this.performanceModel&&(this.performanceModel=null)}createFileSelector(){this.fileSelectorElement&&this.fileSelectorElement.remove(),this.fileSelectorElement=c.UIUtils.createFileSelectorElement(this.loadFromFile.bind(this)),this.timelinePane.element.appendChild(this.fileSelectorElement)}contextMenu(e){const t=new c.ContextMenu.ContextMenu(e);t.appendItemsAtLocation("timelineMenu"),t.show()}async saveToFile(){if(this.state!==Oe.Idle)return;if(!this.performanceModel)return;const e=this.#t.traceEvents(this.#i),t=this.#t.metadata(this.#i);if(!e)return;const i=s.DateUtilities.toISO8601Compact(new Date);let n;n=We?`CPU-${i}.cpuprofile`:`Trace-${i}.json`;try{const i=await window.showSaveFilePicker({suggestedName:n}),r=new TextEncoder;let a;if(We){const t=e.find((e=>"CpuProfile"===e.name));if(!t||!t.args?.data)return;const i=t.args?.data;if(i.hasOwnProperty("cpuProfile")){a=Le(i.cpuProfile)}}else{const i=Ie(e,t);a=Array.from(i).join("")}const s=r.encode(a),o=await i.createWritable();await o.write(s),await o.close()}catch(e){if(console.error(e.stack),"AbortError"===e.name)return;a.Console.Console.instance().error(Ae(He.failedToSaveTimelineSS,{PH1:e.message,PH2:e.name}))}}async showHistory(){const e=await this.historyManager.showHistoryDropDown();e&&e.legacyModel!==this.performanceModel&&this.setModel(e.legacyModel,null,e.traceParseData)}navigateHistory(e){const t=this.historyManager.navigate(e);return t&&t.legacyModel!==this.performanceModel&&this.setModel(t.legacyModel,null,t.traceParseData),!0}selectFileToLoad(){this.fileSelectorElement&&this.fileSelectorElement.click()}async loadFromFile(e){this.state===Oe.Idle&&(this.prepareToLoadTimeline(),this.loader=await pe.loadFromFile(e,this),this.createFileSelector())}async loadFromURL(e){this.state===Oe.Idle&&(this.prepareToLoadTimeline(),this.loader=await pe.loadFromURL(e,this))}updateOverviewControls(){this.overviewControls=[],this.overviewControls.push(new X),this.overviewControls.push(new $),this.overviewControls.push(new q),this.showScreenshotsSetting.get()&&this.filmStripModel&&this.filmStripModel.frames().length&&this.overviewControls.push(new Y(this.filmStripModel)),this.showMemorySetting.get()&&this.overviewControls.push(new K);for(const e of this.overviewControls)e.setModel(this.performanceModel);this.overviewPane.setOverviewControls(this.overviewControls)}onModeChanged(){this.updateOverviewControls(),this.doResize(),this.select(null)}updateSettingsPaneVisibility(){this.showSettingsPaneSetting.get()?this.settingsPane.showWidget():this.settingsPane.hideWidget()}updateShowSettingsToolbarButton(){const e=[];if(1!==n.CPUThrottlingManager.CPUThrottlingManager.instance().cpuThrottlingRate()&&e.push(Ae(He.CpuThrottlingIsEnabled)),g.ThrottlingManager.throttlingManager().hardwareConcurrencyOverrideEnabled&&e.push(Ae(He.HardwareConcurrencyIsEnabled)),n.NetworkManager.MultitargetNetworkManager.instance().isThrottling()&&e.push(Ae(He.NetworkThrottlingIsEnabled)),this.captureLayersAndPicturesSetting.get()&&e.push(Ae(He.SignificantOverheadDueToPaint)),this.disableCaptureJSProfileSetting.get()&&e.push(Ae(He.JavascriptSamplingIsDisabled)),this.showSettingsPaneButton.setDefaultWithRedColor(e.length>0),this.showSettingsPaneButton.setToggleWithRedColor(e.length>0),e.length){const t=document.createElement("div");e.forEach((e=>{t.createChild("div").textContent=e})),this.showSettingsPaneButton.setTitle(t.textContent||"")}else this.showSettingsPaneButton.setTitle(Ae(He.captureSettings))}setUIControlsEnabled(e){this.recordingOptionUIControls.forEach((t=>t.setEnabled(e)))}async#n(){if(!this.controller)return s.DevToolsPath.EmptyUrlString;const e=this.controller.mainTarget(),t=e.inspectedURL(),i=e.model(n.ResourceTreeModel.ResourceTreeModel),r=i&&await i.navigationHistory();if(!i||!r)return t;const{currentIndex:a,entries:o}=r;return o[a].url}async#r(){const e=new Promise((async(e,t)=>{if(!this.controller)return void t("Could not find TimelineController");const i=this.controller.mainTarget().model(n.ResourceTreeModel.ResourceTreeModel);i?(i.addEventListener(n.ResourceTreeModel.Events.FrameNavigated,(function r(a){"about:blank"===a.data.url?e():t(`Unexpected navigation to ${a.data.url}`),i?.removeEventListener(n.ResourceTreeModel.Events.FrameNavigated,r)})),await i.navigate("about:blank")):t("Could not load resourceModel")}));await e}async startRecording(){if(console.assert(!this.statusPane,"Status pane is already opened."),this.setState(Oe.StartPending),We){this.showRecordingStarted();const e=n.TargetManager.TargetManager.instance().targets().find((e=>e.type()===n.Target.Type.Node));e&&(this.cpuProfiler=e.model(n.CPUProfilerModel.CPUProfilerModel)),this.cpuProfiler&&(this.setUIControlsEnabled(!1),this.hideLandingPage(),await n.TargetManager.TargetManager.instance().suspendAllTargets("performance-timeline"),await this.cpuProfiler.startRecording(),this.recordingStarted())}else{const e={enableJSSampling:!this.disableCaptureJSProfileSetting.get(),capturePictures:this.captureLayersAndPicturesSetting.get(),captureFilmStrip:this.showScreenshotsSetting.get()};this.showRecordingStarted();const t=2e3,i=new Promise((e=>setTimeout(e,t))),r=await Promise.race([this.primaryPageTargetPromise,i]);if(!(r instanceof n.Target.Target))return void this.recordingFailed(Ae(He.couldNotStart));if(Ce.isUiDevTools()?this.controller=new Me(r,this):this.controller=new V(r,this),this.setUIControlsEnabled(!1),this.hideLandingPage(),!this.controller)throw new Error("Could not create Timeline controller");const a=await this.#n();try{this.recordingPageReload&&await this.#r();const t=await this.controller.startRecording(e);if(t.getError())throw new Error(t.getError());const i=this.recordingPageReload?{navigateToUrl:a}:void 0;this.recordingStarted(i)}catch(e){this.recordingFailed(e.message)}}}async stopRecording(){if(this.statusPane&&(this.statusPane.finish(),this.statusPane.updateStatus(Ae(He.stoppingTimeline)),this.statusPane.updateProgressBar(Ae(He.received),0)),this.setState(Oe.StopPending),this.controller)return this.performanceModel=this.controller.getPerformanceModel(),await this.controller.stopRecording(),this.setUIControlsEnabled(!0),this.controller.dispose(),void(this.controller=null);if(this.cpuProfiler){const e=await this.cpuProfiler.stopRecording();this.setState(Oe.Idle),this.loadFromCpuProfile(e),this.setUIControlsEnabled(!0),this.cpuProfiler=null,await n.TargetManager.TargetManager.instance().resumeAllTargets()}}recordingFailed(e){this.statusPane&&this.statusPane.remove(),this.statusPane=new ze({description:e,buttonText:Ae(He.close),buttonDisabled:!1,showProgress:void 0,showTimer:void 0},(()=>this.loadingComplete(null))),this.statusPane.showPane(this.statusPaneContainer),this.statusPane.updateStatus(Ae(He.recordingFailed)),this.setState(Oe.RecordingFailed),this.performanceModel=null,this.setUIControlsEnabled(!0),this.controller&&(this.controller.dispose(),this.controller=null)}onSuspendStateChanged(){this.updateTimelineControls()}consoleProfileFinished(e){this.loadFromCpuProfile(e.cpuProfile,e.title),c.InspectorView.InspectorView.instance().showPanel("timeline")}updateTimelineControls(){const e=Oe;this.toggleRecordAction.setToggled(this.state===e.Recording),this.toggleRecordAction.setEnabled(this.state===e.Recording||this.state===e.Idle),this.recordReloadAction.setEnabled(!We&&this.state===e.Idle),this.historyManager.setEnabled(this.state===e.Idle),this.clearButton.setEnabled(this.state===e.Idle),this.panelToolbar.setEnabled(this.state!==e.Loading),this.panelRightToolbar.setEnabled(this.state!==e.Loading),this.dropTarget.setEnabled(this.state===e.Idle),this.loadButton.setEnabled(this.state===e.Idle),this.saveButton.setEnabled(this.state===e.Idle&&Boolean(this.performanceModel))}async toggleRecording(){this.state===Oe.Idle?(this.recordingPageReload=!1,await this.startRecording(),u.userMetrics.actionTaken(u.UserMetrics.Action.TimelineStarted)):this.state===Oe.Recording&&await this.stopRecording()}recordReload(){this.state===Oe.Idle&&(this.recordingPageReload=!0,this.startRecording(),u.userMetrics.actionTaken(u.UserMetrics.Action.TimelinePageReloadStarted))}onClearButton(){this.historyManager.clear(),this.clear()}clear(){this.showLandingPage(),this.reset()}reset(){d.LineLevelProfile.Performance.instance().reset(),this.performanceModel&&this.performanceModel.removeEventListener(Ct.NamesResolved,this.updateModelAndFlameChart,this),this.setModel(null)}applyFilters(e,t=null){e.timelineModel().isGenericTrace()||o.Runtime.experiments.isEnabled("timelineShowAllEvents")||e.setFilters(t?[t]:[ct.visibleEventsFilter()])}setModel(e,t=null,i=null,n=null){if(this.performanceModel&&this.performanceModel.removeEventListener(Ct.WindowChanged,this.onModelWindowChanged,this),this.performanceModel=e,e?(this.searchableViewInternal.showWidget(),this.applyFilters(e,t)):this.searchableViewInternal.hideWidget(),this.flameChart.setModel(e,i,n),this.updateOverviewControls(),this.overviewPane.reset(),e&&this.performanceModel){this.performanceModel.addEventListener(Ct.WindowChanged,this.onModelWindowChanged,this),this.overviewPane.setNavStartTimes(e.timelineModel().navStartTimes()),this.overviewPane.setBounds(e.timelineModel().minimumRecordTime(),e.timelineModel().maximumRecordTime()),d.LineLevelProfile.Performance.instance().reset();for(const t of e.timelineModel().cpuProfiles())d.LineLevelProfile.Performance.instance().appendCPUProfile(t);this.setMarkers(e.timelineModel()),this.flameChart.setSelection(null),this.overviewPane.setWindowTimes(e.window().left,e.window().right)}for(const t of this.overviewControls)t.setModel(e);this.flameChart&&this.flameChart.resizeToPreferredHeights(),this.updateTimelineControls()}recordingStarted(e){if(e&&this.recordingPageReload&&this.controller){const t=this.controller.mainTarget().model(n.ResourceTreeModel.ResourceTreeModel);if(!t)return void this.recordingFailed("Could not navigate to original URL");t.navigate(e.navigateToUrl)}this.reset(),this.setState(Oe.Recording),this.showRecordingStarted(),this.statusPane&&(this.statusPane.enableAndFocusButton(),this.statusPane.updateStatus(Ae(He.profiling)),this.statusPane.updateProgressBar(Ae(He.bufferUsage),0),this.statusPane.startTimer()),this.hideLandingPage()}recordingProgress(e){this.statusPane&&this.statusPane.updateProgressBar(Ae(He.bufferUsage),100*e)}showLandingPage(){if(this.landingPage)return void this.landingPage.show(this.statusPaneContainer);function e(e,t){const i=document.createElement(e);return i.textContent=t,i}const t=c.XLink.XLink.create("https://developer.chrome.com/docs/devtools/evaluate-performance/",Ae(He.learnmore)),n=e("b",c.ShortcutRegistry.ShortcutRegistry.instance().shortcutsForAction("timeline.toggle-recording")[0].title()),r=e("b",c.ShortcutRegistry.ShortcutRegistry.instance().shortcutsForAction("timeline.record-reload")[0].title()),a=e("b",Ae(He.wasd));this.landingPage=new c.Widget.VBox,this.landingPage.contentElement.classList.add("timeline-landing-page","fill");const s=this.landingPage.contentElement.createChild("div"),o=c.UIUtils.createInlineButton(c.Toolbar.Toolbar.createActionButton(this.toggleRecordAction)),l=c.UIUtils.createInlineButton(c.Toolbar.Toolbar.createActionButtonForId("timeline.record-reload"));if(s.createChild("p").appendChild(i.i18n.getFormatLocalizedString(Ne,He.clickTheRecordButtonSOrHitSTo,{PH1:o,PH2:n})),s.createChild("p").appendChild(i.i18n.getFormatLocalizedString(Ne,He.clickTheReloadButtonSOrHitSTo,{PH1:l,PH2:r})),s.createChild("p").appendChild(i.i18n.getFormatLocalizedString(Ne,He.afterRecordingSelectAnAreaOf,{PH1:a,PH2:t})),We){const e=new p.PanelFeedback.PanelFeedback;e.data={feedbackUrl:"https://bugs.chromium.org/p/chromium/issues/detail?id=1354548",quickStartUrl:"https://developer.chrome.com/blog/js-profiler-deprecation/",quickStartLinkText:Ae(He.learnmore)},s.appendChild(e);const t=new p.FeedbackButton.FeedbackButton;t.data={feedbackUrl:"https://bugs.chromium.org/p/chromium/issues/detail?id=1354548"},s.appendChild(t)}this.landingPage.show(this.statusPaneContainer)}hideLandingPage(){this.landingPage.detach()}async loadingStarted(){this.hideLandingPage(),this.statusPane&&this.statusPane.remove(),this.statusPane=new ze({showProgress:!0,showTimer:void 0,buttonDisabled:void 0,buttonText:void 0,description:void 0},(()=>this.cancelLoading())),this.statusPane.showPane(this.statusPaneContainer),this.statusPane.updateStatus(Ae(He.loadingProfile)),this.loader||this.statusPane.finish(),await this.loadingProgress(0)}async loadingProgress(e){"number"==typeof e&&this.statusPane&&this.statusPane.updateProgressBar(Ae(He.received),100*e)}async processingStarted(){this.statusPane&&this.statusPane.updateStatus(Ae(He.processingProfile))}updateModelAndFlameChart(){this.performanceModel&&(this.setModel(this.performanceModel),this.flameChart.updateColorMapper())}async loadingComplete(e,t=null){this.#t.reset(),delete this.loader;const i=this.state===Oe.StopPending;if(this.setState(Oe.Idle),e){this.performanceModel||(this.performanceModel=new bt);try{await Promise.all([this.performanceModel.setTracingModel(e,i),this.#a(e,i,this.performanceModel.recordStartTime())]);const r=this.#t.traceParsedData();this.filmStripModel=new n.FilmStripModel.FilmStripModel(e),this.setModel(this.performanceModel,t,r,this.filmStripModel),this.#i=this.#t.size()-1,this.statusPane&&this.statusPane.remove(),this.statusPane=null,this.performanceModel.hasEventListeners(Ct.NamesResolved)||this.performanceModel.addEventListener(Ct.NamesResolved,this.updateModelAndFlameChart,this),this.historyManager.addRecording(this.performanceModel,r,this.filmStripModel)}catch(e){this.recordingFailed(e.message),console.error(e)}}else this.clear()}async#a(e,t,i){const r=t&&!We?await n.TraceSDKServices.getMetadataForFreshRecording(i):void 0;return this.#t.parse(e.allRawEvents(),{metadata:r,isFreshRecording:t})}loadingCompleteForTest(){}showRecordingStarted(){this.statusPane||(this.statusPane=new ze({showTimer:!0,showProgress:!0,buttonDisabled:!0,description:void 0,buttonText:void 0},(()=>this.stopRecording())),this.statusPane.showPane(this.statusPaneContainer),this.statusPane.updateStatus(Ae(He.initializingProfiler)))}cancelLoading(){this.loader&&this.loader.cancel()}setMarkers(e){const t=new Map,i=r.TimelineModel.RecordType,n=e.minimumRecordTime();for(const r of e.timeMarkerEvents())r.name!==i.TimeStamp&&r.name!==i.ConsoleTime&&t.set(r.startTime,ct.createEventDivider(r,n));for(const i of e.navStartTimes().values())t.set(i.startTime,ct.createEventDivider(i,n));this.overviewPane.setMarkers(t)}async loadEventFired(e){if(this.state!==Oe.Recording||!this.recordingPageReload||!this.controller||this.controller.mainTarget()!==e.data.resourceTreeModel.target())return;const t=this.controller;await new Promise((e=>window.setTimeout(e,this.millisecondsToRecordAfterLoadEvent))),t===this.controller&&this.state===Oe.Recording&&this.stopRecording()}frameForSelection(e){return De.isFrameObject(e.object)?e.object:De.isRangeSelection(e.object)||De.isNetworkRequestSelection(e.object)?null:De.isTraceEventSelection(e.object)?this.performanceModel?this.performanceModel.frameModel().getFramesWithinWindow(e.endTime,e.endTime)[0]:null:(console.assert(!1,"Should never be reached"),null)}jumpToFrame(e){const t=this.selection&&this.frameForSelection(this.selection);if(!t||!this.performanceModel)return;const i=this.performanceModel.frames();let n=i.indexOf(t);console.assert(n>=0,"Can't find current frame in the frame list"),n=s.NumberUtilities.clamp(n+e,0,i.length-1);const r=i[n];return this.revealTimeRange(r.startTime,r.endTime),this.select(De.fromFrame(r)),!0}select(e){this.selection=e,this.flameChart.setSelection(e)}selectEntryAtTime(e,t){if(e){for(let i=s.ArrayUtilities.upperBound(e,t,((e,t)=>e-t.startTime))-1;i>=0;--i){const r=e[i],a=r.endTime||r.startTime;if(n.TracingModel.TracingModel.isTopLevelEvent(r)&&a<t)break;if(this.performanceModel&&this.performanceModel.isVisible(r)&&a>=t)return void this.select(De.fromTraceEvent(r))}this.select(null)}}highlightEvent(e){this.flameChart.highlightEvent(e)}revealTimeRange(e,t){if(!this.performanceModel)return;const i=this.performanceModel.window();let n=0;i.right<t?n=t-i.right:i.left>e&&(n=e-i.left),this.performanceModel.setWindow({left:i.left+n,right:i.right+n},!0)}handleDrop(e){const t=e.items;if(!t.length)return;const i=t[0];if(u.userMetrics.actionTaken(u.UserMetrics.Action.PerfPanelTraceImported),"string"===i.kind){const t=e.getData("text/uri-list");new a.ParsedURL.ParsedURL(t).isValid&&this.loadFromURL(t)}else if("file"===i.kind){const e=t[0].getAsFile();if(!e)return;this.loadFromFile(e)}}}var Oe;!function(e){e.Idle="Idle",e.StartPending="StartPending",e.Recording="Recording",e.StopPending="StopPending",e.Loading="Loading",e.RecordingFailed="RecordingFailed"}(Oe||(Oe={}));class ze extends c.Widget.VBox{status;time;progressLabel;progressBar;description;button;startTime;timeUpdateTimer;constructor(e,t){super(!0),this.contentElement.classList.add("timeline-status-dialog");const i=this.contentElement.createChild("div","status-dialog-line status");if(i.createChild("div","label").textContent=Ae(He.status),this.status=i.createChild("div","content"),c.ARIAUtils.markAsStatus(this.status),e.showTimer){const e=this.contentElement.createChild("div","status-dialog-line time");e.createChild("div","label").textContent=Ae(He.time),this.time=e.createChild("div","content")}if(e.showProgress){const e=this.contentElement.createChild("div","status-dialog-line progress");this.progressLabel=e.createChild("div","label"),this.progressBar=e.createChild("div","indicator-container").createChild("div","indicator"),c.ARIAUtils.markAsProgressBar(this.progressBar)}if("string"==typeof e.description){const t=this.contentElement.createChild("div","status-dialog-line description");t.createChild("div","label").textContent=Ae(He.description),this.description=t.createChild("div","content"),this.description.innerText=e.description}const n=e.buttonText||Ae(He.stop);this.button=c.UIUtils.createTextButton(n,t,"",!0),this.button.disabled=!1==!e.buttonDisabled,this.contentElement.createChild("div","stop-button").appendChild(this.button)}finish(){this.stopTimer(),this.button.disabled=!0}remove(){this.element.parentNode.classList.remove("tinted"),this.arrangeDialog(this.element.parentNode),this.stopTimer(),this.element.remove()}showPane(e){this.arrangeDialog(e),this.show(e),e.classList.add("tinted")}enableAndFocusButton(){this.button.disabled=!1,this.button.focus()}updateStatus(e){this.status.textContent=e}updateProgressBar(e,t){this.progressLabel.textContent=e,this.progressBar.style.width=t.toFixed(1)+"%",c.ARIAUtils.setValueNow(this.progressBar,t),this.updateTimer()}startTimer(){this.startTime=Date.now(),this.timeUpdateTimer=window.setInterval(this.updateTimer.bind(this,!1),1e3),this.updateTimer()}stopTimer(){this.timeUpdateTimer&&(clearInterval(this.timeUpdateTimer),this.updateTimer(!0),delete this.timeUpdateTimer)}updateTimer(e){if(this.arrangeDialog(this.element.parentNode),!this.timeUpdateTimer||!this.time)return;const t=(Date.now()-this.startTime)/1e3;this.time.textContent=Ae(He.ssec,{PH1:t.toFixed(e?1:0)})}arrangeDialog(e){const t=e.clientWidth<325;this.element.classList.toggle("small-dialog",t),this.contentElement.classList.toggle("small-dialog",t)}wasShown(){super.wasShown(),this.registerCSSFiles([N])}}let Ge,_e;class je{static instance(e={forceNew:null}){const{forceNew:t}=e;return Ge&&!t||(Ge=new je),Ge}handleQueryParam(e){c.ViewManager.ViewManager.instance().showView("timeline").then((async()=>{await Ve.instance().loadFromURL(window.decodeURIComponent(e))}))}}class qe{static instance(e={forceNew:null}){const{forceNew:t}=e;return _e&&!t||(_e=new qe),_e}handleAction(e,t){const i=c.Context.Context.instance().flavor(Ve);switch(console.assert(i&&i instanceof Ve),t){case"timeline.toggle-recording":return i.toggleRecording(),!0;case"timeline.record-reload":return i.recordReload(),!0;case"timeline.save-to-file":return i.saveToFile(),!0;case"timeline.load-from-file":return i.selectFileToLoad(),!0;case"timeline.jump-to-previous-frame":return i.jumpToFrame(-1),!0;case"timeline.jump-to-next-frame":return i.jumpToFrame(1),!0;case"timeline.show-history":return i.showHistory(),!0;case"timeline.previous-recording":return i.navigateHistory(1),!0;case"timeline.next-recording":return i.navigateHistory(-1),!0}return!1}}var Je=Object.freeze({__proto__:null,TimelinePanel:Ve,get State(){return Oe},rowHeight:18,headerHeight:20,StatusPane:ze,LoadTimelineHandler:je,ActionDelegate:qe});const $e={interactions:"Interactions"},Xe=i.i18n.registerUIStrings("panels/timeline/InteractionsTrackAppender.ts",$e),Ye=i.i18n.getLocalizedString.bind(void 0,Xe),Ke=e.Helpers.Timing.millisecondsToMicroseconds(e.Types.Timing.MilliSeconds(200));class Ze{appenderName="Interactions";#s;#o;#l;#d;constructor(e,t,i,n){this.#o=e,this.#s=n,this.#l=t,this.#d=i}appendTrackAtLevel(e,t){return 0===this.#d.UserInteractions.interactionEvents.length?e:(this.#c(e,t),this.#h(e))}#c(e,t){const i=b({shareHeaderLine:!1,collapsible:this.#d.UserInteractions.interactionEvents.length>0}),n=C(e,Ye($e.interactions),i,!0,t);this.#o.registerTrackForGroup(n,this)}#h(t){const i=this.#d.UserInteractions.interactionEventsWithNoNesting,n=this.#o.appendEventsAtLevel(i,t,this);for(let t=0;t<i.length;++t){if((i[t].dur||e.Types.Timing.MicroSeconds(0))<=Ke)continue;const n=this.#o.indexForEvent(i[t]);void 0!==n&&this.#m(n)}return n}#m(e){const t=this.#l.entryDecorations[e]||[];t.push({type:"CANDY",startAtTime:Ke}),this.#l.entryDecorations[e]=t}colorForEvent(t){let i=this.titleForEvent(t);return e.Types.TraceEvents.isSyntheticInteractionEvent(t)&&(i+=t.interactionId),this.#s.colorForID(i)}titleForEvent(t){return e.Types.TraceEvents.isSyntheticInteractionEvent(t)?Qe(t):t.name}highlightedEntryInfo(e){return{title:this.titleForEvent(e),formattedTime:k(e.dur)}}}function Qe(t){const i=e.Handlers.ModelHandlers.UserInteractions.categoryOfInteraction(t);return"OTHER"===i?"Other":"KEYBOARD"===i?"Keyboard":"POINTER"===i?"Pointer":t.type}var et=Object.freeze({__proto__:null,InteractionsTrackAppender:Ze,titleForInteractionEvent:Qe});const tt={sAndS:"{PH1} and {PH2}",sAndSOther:"{PH1}, {PH2}, and 1 other",task:"Task",other:"Other",animation:"Animation",event:"Event",requestMainThreadFrame:"Request Main Thread Frame",frameStart:"Frame Start",frameStartMainThread:"Frame Start (main thread)",drawFrame:"Draw Frame",profilingOverhead:"Profiling Overhead",hitTest:"Hit Test",scheduleStyleRecalculation:"Schedule Style Recalculation",recalculateStyle:"Recalculate Style",invalidateLayout:"Invalidate Layout",layerize:"Layerize",layout:"Layout",paintSetup:"Paint Setup",paintImage:"Paint Image",prePaint:"Pre-Paint",updateLayer:"Update Layer",updateLayerTree:"Update Layer Tree",paint:"Paint",rasterizePaint:"Rasterize Paint",scroll:"Scroll",commit:"Commit",compositeLayers:"Composite Layers",computeIntersections:"Compute Intersections",parseHtml:"Parse HTML",parseStylesheet:"Parse Stylesheet",installTimer:"Install Timer",removeTimer:"Remove Timer",timerFired:"Timer Fired",xhrReadyStateChange:"`XHR` Ready State Change",xhrLoad:"`XHR` Load",compileScript:"Compile Script",cacheScript:"Cache Script Code",compileCode:"Compile Code",optimizeCode:"Optimize Code",evaluateScript:"Evaluate Script",compileModule:"Compile Module",cacheModule:"Cache Module Code",evaluateModule:"Evaluate Module",streamingCompileTask:"Streaming Compile Task",waitingForNetwork:"Waiting for Network",parseAndCompile:"Parse and Compile",deserializeCodeCache:"Deserialize Code Cache",streamingWasmResponse:"Streaming Wasm Response",compiledWasmModule:"Compiled Wasm Module",cachedWasmModule:"Cached Wasm Module",wasmModuleCacheHit:"Wasm Module Cache Hit",wasmModuleCacheInvalid:"Wasm Module Cache Invalid",frameStartedLoading:"Frame Started Loading",onloadEvent:"Onload Event",domcontentloadedEvent:"DOMContentLoaded Event",firstPaint:"First Paint",firstContentfulPaint:"First Contentful Paint",largestContentfulPaint:"Largest Contentful Paint",timestamp:"Timestamp",consoleTime:"Console Time",userTiming:"User Timing",willSendRequest:"Will Send Request",sendRequest:"Send Request",receiveResponse:"Receive Response",finishLoading:"Finish Loading",receiveData:"Receive Data",runMicrotasks:"Run Microtasks",functionCall:"Function Call",gcEvent:"GC Event",majorGc:"Major GC",minorGc:"Minor GC",jsRoot:"JS Root",jsFrame:"JS Frame",jsIdleFrame:"JS Idle Frame",jsSystemFrame:"JS System Frame",requestAnimationFrame:"Request Animation Frame",interactionID:"ID",cancelAnimationFrame:"Cancel Animation Frame",animationFrameFired:"Animation Frame Fired",requestIdleCallback:"Request Idle Callback",cancelIdleCallback:"Cancel Idle Callback",fireIdleCallback:"Fire Idle Callback",createWebsocket:"Create WebSocket",sendWebsocketHandshake:"Send WebSocket Handshake",receiveWebsocketHandshake:"Receive WebSocket Handshake",destroyWebsocket:"Destroy WebSocket",embedderCallback:"Embedder Callback",imageDecode:"Image Decode",imageResize:"Image Resize",gpu:"GPU",domGc:"DOM GC",encrypt:"Encrypt",encryptReply:"Encrypt Reply",decrypt:"Decrypt",decryptReply:"Decrypt Reply",digest:"Digest",digestReply:"Digest Reply",sign:"Sign",signReply:"Sign Reply",verify:"Verify",verifyReply:"Verify Reply",asyncTask:"Async Task",layoutShift:"Layout Shift",eventTiming:"Event Timing",compile:"Compile",parse:"Parse",sS:"{PH1}: {PH2}",sCollected:"{PH1} collected",sSs:"{PH1} [{PH2}…{PH3}]",sSSquareBrackets:"{PH1} [{PH2}…]",learnMore:"Learn more",compilationCacheStatus:"Compilation cache status",compilationCacheSize:"Compilation cache size",scriptLoadedFromCache:"script loaded from cache",failedToLoadScriptFromCache:"failed to load script from cache",scriptNotEligible:"script not eligible",totalTime:"Total Time",selfTime:"Self Time",collected:"Collected",function:"Function",timerId:"Timer ID",timeout:"Timeout",repeats:"Repeats",callbackId:"Callback ID",resource:"Resource",requestMethod:"Request Method",statusCode:"Status Code",mimeTypeCaps:"MIME Type",priority:"Priority",encodedData:"Encoded Data",sBytes:"{n, plural, =1 {# Byte} other {# Bytes}}",decodedBody:"Decoded Body",module:"Module",script:"Script",streamed:"Streamed",eagerCompile:"Compiling all functions eagerly",url:"Url",producedCacheSize:"Produced Cache Size",consumedCacheSize:"Consumed Cache Size",location:"Location",sSCurlyBrackets:"({PH1}, {PH2})",dimensions:"Dimensions",sSDimensions:"{PH1} × {PH2}",layerRoot:"Layer Root",ownerElement:"Owner Element",imageUrl:"Image URL",stylesheetUrl:"Stylesheet URL",elementsAffected:"Elements Affected",nodesThatNeedLayout:"Nodes That Need Layout",sOfS:"{PH1} of {PH2}",layoutRoot:"Layout root",message:"Message",websocketProtocol:"WebSocket Protocol",callbackFunction:"Callback Function",state:"State",range:"Range",allottedTime:"Allotted Time",invokedByTimeout:"Invoked by Timeout",type:"Type",size:"Size",details:"Details",cumulativeLayoutShifts:"Cumulative Layout Shifts",evolvedClsLink:"evolved",sCLSInformation:"{PH1} can result in poor user experiences. It has recently {PH2}.",warning:"Warning",score:"Score",cumulativeScore:"Cumulative Score",currentClusterScore:"Current Cluster Score",currentClusterId:"Current Cluster ID",hadRecentInput:"Had recent input",yes:"Yes",no:"No",movedFrom:"Moved from",movedTo:"Moved to",relatedNode:"Related Node",preview:"Preview",aggregatedTime:"Aggregated Time",networkRequest:"Network request",loadFromCache:"load from cache",networkTransfer:"network transfer",SSSResourceLoading:" ({PH1} {PH2} + {PH3} resource loading)",duration:"Duration",mimeType:"Mime Type",FromMemoryCache:" (from memory cache)",FromCache:" (from cache)",FromPush:" (from push)",FromServiceWorker:" (from `service worker`)",initiator:"Initiator",timerInstalled:"Timer Installed",animationFrameRequested:"Animation Frame Requested",idleCallbackRequested:"Idle Callback Requested",recalculationForced:"Recalculation Forced",firstLayoutInvalidation:"First Layout Invalidation",layoutForced:"Layout Forced",callStacks:"Call Stacks",stackTrace:"Stack Trace",invalidations:"Invalidations",pendingFor:"Pending for",reveal:"Reveal",firstInvalidated:"First Invalidated",styleInvalidations:"Style Invalidations",layoutInvalidations:"Layout Invalidations",otherInvalidations:"Other Invalidations",paintProfiler:"Paint Profiler",sAtS:"{PH1} at {PH2}",loading:"Loading",experience:"Experience",scripting:"Scripting",rendering:"Rendering",painting:"Painting",async:"Async",system:"System",idle:"Idle",sSelf:"{PH1} (self)",sChildren:"{PH1} (children)",timeSpentInRendering:"Time spent in rendering",frame:"Frame",cpuTime:"CPU time",layerTree:"Layer tree",show:"Show",sAtSParentheses:"{PH1} (at {PH2})",emptyPlaceholder:"{PH1}",jank:"jank",sLongFrameTimesAreAnIndicationOf:"{PH1}. Long frame times are an indication of {PH2}",forcedReflow:"Forced reflow",longInteractionINP:"Long interaction",sIsLikelyPoorPageResponsiveness:"{PH1} is indicating poor page responsiveness.",sIsALikelyPerformanceBottleneck:"{PH1} is a likely performance bottleneck.",idleCallbackExecutionExtended:"Idle callback execution extended beyond deadline by {PH1}",handlerTookS:"Handler took {PH1}",recurringHandlerTookS:"Recurring handler took {PH1}",longTask:"Long task",sTookS:"{PH1} took {PH2}.",notOptimized:"Not optimized",emptyPlaceholderColon:": {PH1}",unknownCause:"Unknown cause",sForS:"{PH1} for {PH2}",sSDot:"{PH1}. {PH2}",unknown:"unknown",stackTraceColon:"Stack trace:",nodes:"Nodes:",node:"Node:",changedIdToSs:'(changed id to "{PH1}"{PH2})',changedClassToSs:'(changed class to "{PH1}"{PH2})',changedAttributeToSs:'(changed attribute to "{PH1}"{PH2})',changedPesudoToSs:'(changed pseudo to "{PH1}"{PH2})',changedSs:'(changed "{PH1}"{PH2})',sSAndSOthers:"{PH1}, {PH2}, and {PH3} others",UnknownNode:"[ unknown node ]"},it=i.i18n.registerUIStrings("panels/timeline/TimelineUIUtils.ts",tt),nt=i.i18n.getLocalizedString.bind(void 0,it);let rt,at,st,ot,lt;const dt=new WeakMap;class ct{static initEventStyles(){if(rt)return rt;const e=r.TimelineModel.RecordType,t=ct.categories(),i=t.rendering,n=t.scripting,a=t.loading,s=t.experience,o=t.painting,l=t.other,d=t.idle,c={};return c[e.Task]=new ht(nt(tt.task),l),c[e.Program]=new ht(nt(tt.other),l),c[e.StartProfiling]=new ht(tt.profilingOverhead,l),c[e.Animation]=new ht(nt(tt.animation),i),c[e.EventDispatch]=new ht(nt(tt.event),n),c[e.RequestMainThreadFrame]=new ht(nt(tt.requestMainThreadFrame),i,!0),c[e.BeginFrame]=new ht(nt(tt.frameStart),i,!0),c[e.BeginMainThreadFrame]=new ht(nt(tt.frameStartMainThread),i,!0),c[e.DrawFrame]=new ht(nt(tt.drawFrame),i,!0),c[e.HitTest]=new ht(nt(tt.hitTest),i),c[e.ScheduleStyleRecalculation]=new ht(nt(tt.scheduleStyleRecalculation),i),c[e.RecalculateStyles]=new ht(nt(tt.recalculateStyle),i),c[e.UpdateLayoutTree]=new ht(nt(tt.recalculateStyle),i),c[e.InvalidateLayout]=new ht(nt(tt.invalidateLayout),i,!0),c[e.Layerize]=new ht(nt(tt.layerize),i),c[e.Layout]=new ht(nt(tt.layout),i),c[e.PaintSetup]=new ht(nt(tt.paintSetup),o),c[e.PaintImage]=new ht(nt(tt.paintImage),o,!0),c[e.UpdateLayer]=new ht(nt(tt.updateLayer),o,!0),c[e.UpdateLayerTree]=new ht(nt(tt.updateLayerTree),i),c[e.Paint]=new ht(nt(tt.paint),o),c[e.PrePaint]=new ht(nt(tt.prePaint),i),c[e.RasterTask]=new ht(nt(tt.rasterizePaint),o),c[e.ScrollLayer]=new ht(nt(tt.scroll),i),c[e.Commit]=new ht(nt(tt.commit),o),c[e.CompositeLayers]=new ht(nt(tt.compositeLayers),o),c[e.ComputeIntersections]=new ht(nt(tt.computeIntersections),i),c[e.ParseHTML]=new ht(nt(tt.parseHtml),a),c[e.ParseAuthorStyleSheet]=new ht(nt(tt.parseStylesheet),a),c[e.TimerInstall]=new ht(nt(tt.installTimer),n),c[e.TimerRemove]=new ht(nt(tt.removeTimer),n),c[e.TimerFire]=new ht(nt(tt.timerFired),n),c[e.XHRReadyStateChange]=new ht(nt(tt.xhrReadyStateChange),n),c[e.XHRLoad]=new ht(nt(tt.xhrLoad),n),c[e.CompileScript]=new ht(nt(tt.compileScript),n),c[e.CacheScript]=new ht(nt(tt.cacheScript),n),c[e.CompileCode]=new ht(nt(tt.compileCode),n),c[e.OptimizeCode]=new ht(nt(tt.optimizeCode),n),c[e.EvaluateScript]=new ht(nt(tt.evaluateScript),n),c[e.CompileModule]=new ht(nt(tt.compileModule),n),c[e.CacheModule]=new ht(nt(tt.cacheModule),n),c[e.EvaluateModule]=new ht(nt(tt.evaluateModule),n),c[e.StreamingCompileScript]=new ht(nt(tt.streamingCompileTask),l),c[e.StreamingCompileScriptWaiting]=new ht(nt(tt.waitingForNetwork),d),c[e.StreamingCompileScriptParsing]=new ht(nt(tt.parseAndCompile),n),c[e.BackgroundDeserialize]=new ht(nt(tt.deserializeCodeCache),n),c[e.FinalizeDeserialization]=new ht(tt.profilingOverhead,l),c[e.WasmStreamFromResponseCallback]=new ht(nt(tt.streamingWasmResponse),n),c[e.WasmCompiledModule]=new ht(nt(tt.compiledWasmModule),n),c[e.WasmCachedModule]=new ht(nt(tt.cachedWasmModule),n),c[e.WasmModuleCacheHit]=new ht(nt(tt.wasmModuleCacheHit),n),c[e.WasmModuleCacheInvalid]=new ht(nt(tt.wasmModuleCacheInvalid),n),c[e.FrameStartedLoading]=new ht(nt(tt.frameStartedLoading),a,!0),c[e.MarkLoad]=new ht(nt(tt.onloadEvent),n,!0),c[e.MarkDOMContent]=new ht(nt(tt.domcontentloadedEvent),n,!0),c[e.MarkFirstPaint]=new ht(nt(tt.firstPaint),o,!0),c[e.MarkFCP]=new ht(nt(tt.firstContentfulPaint),i,!0),c[e.MarkLCPCandidate]=new ht(nt(tt.largestContentfulPaint),i,!0),c[e.TimeStamp]=new ht(nt(tt.timestamp),n),c[e.ConsoleTime]=new ht(nt(tt.consoleTime),n),c[e.UserTiming]=new ht(nt(tt.userTiming),n),c[e.ResourceWillSendRequest]=new ht(nt(tt.willSendRequest),a),c[e.ResourceSendRequest]=new ht(nt(tt.sendRequest),a),c[e.ResourceReceiveResponse]=new ht(nt(tt.receiveResponse),a),c[e.ResourceFinish]=new ht(nt(tt.finishLoading),a),c[e.ResourceReceivedData]=new ht(nt(tt.receiveData),a),c[e.RunMicrotasks]=new ht(nt(tt.runMicrotasks),n),c[e.FunctionCall]=new ht(nt(tt.functionCall),n),c[e.GCEvent]=new ht(nt(tt.gcEvent),n),c[e.MajorGC]=new ht(nt(tt.majorGc),n),c[e.MinorGC]=new ht(nt(tt.minorGc),n),c[e.JSRoot]=new ht(nt(tt.jsRoot),d,!0),c[e.JSFrame]=new ht(nt(tt.jsFrame),n),c[e.JSIdleFrame]=new ht(nt(tt.jsIdleFrame),d,!0),c[e.JSSystemFrame]=new ht(nt(tt.jsSystemFrame),l,!0),c[e.RequestAnimationFrame]=new ht(nt(tt.requestAnimationFrame),n),c[e.CancelAnimationFrame]=new ht(nt(tt.cancelAnimationFrame),n),c[e.FireAnimationFrame]=new ht(nt(tt.animationFrameFired),n),c[e.RequestIdleCallback]=new ht(nt(tt.requestIdleCallback),n),c[e.CancelIdleCallback]=new ht(nt(tt.cancelIdleCallback),n),c[e.FireIdleCallback]=new ht(nt(tt.fireIdleCallback),n),c[e.WebSocketCreate]=new ht(nt(tt.createWebsocket),n),c[e.WebSocketSendHandshakeRequest]=new ht(nt(tt.sendWebsocketHandshake),n),c[e.WebSocketReceiveHandshakeResponse]=new ht(nt(tt.receiveWebsocketHandshake),n),c[e.WebSocketDestroy]=new ht(nt(tt.destroyWebsocket),n),c[e.EmbedderCallback]=new ht(nt(tt.embedderCallback),n),c[e.DecodeImage]=new ht(nt(tt.imageDecode),o),c[e.ResizeImage]=new ht(nt(tt.imageResize),o),c[e.GPUTask]=new ht(nt(tt.gpu),t.gpu),c[e.GCCollectGarbage]=new ht(nt(tt.domGc),n),c[e.CryptoDoEncrypt]=new ht(nt(tt.encrypt),n),c[e.CryptoDoEncryptReply]=new ht(nt(tt.encryptReply),n),c[e.CryptoDoDecrypt]=new ht(nt(tt.decrypt),n),c[e.CryptoDoDecryptReply]=new ht(nt(tt.decryptReply),n),c[e.CryptoDoDigest]=new ht(nt(tt.digest),n),c[e.CryptoDoDigestReply]=new ht(nt(tt.digestReply),n),c[e.CryptoDoSign]=new ht(nt(tt.sign),n),c[e.CryptoDoSignReply]=new ht(nt(tt.signReply),n),c[e.CryptoDoVerify]=new ht(nt(tt.verify),n),c[e.CryptoDoVerifyReply]=new ht(nt(tt.verifyReply),n),c[e.AsyncTask]=new ht(nt(tt.asyncTask),t.async),c[e.LayoutShift]=new ht(nt(tt.layoutShift),s),c[e.EventTiming]=new ht(tt.eventTiming,s),rt=c,c}static setEventStylesMap(e){rt=e}static frameDisplayName(e){if(!r.TimelineJSProfile.TimelineJSProfileProcessor.isNativeRuntimeFrame(e))return c.UIUtils.beautifyFunctionName(e.functionName);const t=r.TimelineJSProfile.TimelineJSProfileProcessor.nativeGroup(e.functionName),i=r.TimelineJSProfile.TimelineJSProfileProcessor.NativeGroups;switch(t){case i.Compile:return nt(tt.compile);case i.Parse:return nt(tt.parse)}return e.functionName}static testContentMatching(e,t){const i=[ct.eventStyle(e).title],n=r.TimelineModel.EventOnTimelineData.forEvent(e).url;return n&&i.push(n),function e(t,n){if(!n)return;for(const r in t){const a=t[r];"string"==typeof a?i.push(a):"number"==typeof a?i.push(String(a)):"object"==typeof a&&null!==a&&e(a,n-1)}}(e.args,2),t.test(i.join("|"))}static eventURL(e){const t=e.args.data||e.args.beginData,i=t&&t.url;if(i)return i;const n=t&&t.stackTrace,a=n&&n.length&&n[0]||r.TimelineModel.EventOnTimelineData.forEvent(e).topFrame();return a&&a.url||null}static eventStyle(e){const t=ct.initEventStyles();if(n.TracingModel.eventHasCategory(e,r.TimelineModel.TimelineModelImpl.Category.Console)||n.TracingModel.eventHasCategory(e,r.TimelineModel.TimelineModelImpl.Category.UserTiming))return new ht(e.name,ct.categories().scripting);let i=t[e.name];return i||(i=new ht(e.name,ct.categories().other,!0),t[e.name]=i),i}static eventColor(e){if(r.TimelineModel.TimelineModelImpl.isJsFrameEvent(e)){const t=e.args.data;if(ct.isUserFrame(t))return ct.colorForId(t.url)}const t=ct.eventStyle(e).category.color;if(e.name===r.TimelineModel.RecordType.StreamingCompileScriptWaiting){const e=a.Color.parse(ct.categories().scripting.color);if(!e)throw new Error("Unable to parse color from TimelineUIUtils.categories().scripting.color");return e.setAlpha(.3).asString()}return t}static eventTitle(t){const i=r.TimelineModel.RecordType,a=t.args.data;if(r.TimelineModel.TimelineModelImpl.isJsFrameEvent(t))return ct.frameDisplayName(a);if("EventTiming"===t.name){let i=null;if(t instanceof n.TracingModel.PayloadEvent?i=t.rawPayload():n.TracingModel.eventIsFromNewEngine(t)&&(i=t),i&&e.Types.TraceEvents.isSyntheticInteractionEvent(i))return Qe(i)}const s=ct.eventStyle(t).title;return n.TracingModel.eventHasCategory(t,r.TimelineModel.TimelineModelImpl.Category.Console)?s:t.name===i.TimeStamp?nt(tt.sS,{PH1:s,PH2:a.message}):t.name===i.Animation&&a&&a.name?nt(tt.sS,{PH1:s,PH2:a.name}):t.name===i.EventDispatch&&a&&a.type?nt(tt.sS,{PH1:s,PH2:a.type}):s}static isUserFrame(e){return"0"!==e.scriptId&&!(e.url&&e.url.startsWith("native "))}static networkRequestCategory(e){const t=mt;switch(e.mimeType){case"text/html":return t.HTML;case"application/javascript":case"application/x-javascript":case"text/javascript":return t.Script;case"text/css":return t.Style;case"audio/ogg":case"image/gif":case"image/jpeg":case"image/png":case"image/svg+xml":case"image/webp":case"image/x-icon":case"font/opentype":case"font/woff2":case"application/font-woff":return t.Media;default:return t.Other}}static networkCategoryColor(e){const t=mt;switch(e){case t.HTML:return"hsl(214, 67%, 66%)";case t.Script:return"hsl(43, 83%, 64%)";case t.Style:return"hsl(256, 67%, 70%)";case t.Media:return"hsl(109, 33%, 55%)";default:return"hsl(0, 0%, 70%)"}}static async buildDetailsTextForTraceEvent(e){const t=r.TimelineModel.RecordType;let i;const a=e.args.data;switch(e.name){case t.GCEvent:case t.MajorGC:case t.MinorGC:{const t=e.args.usedHeapSizeBefore-e.args.usedHeapSizeAfter;i=nt(tt.sCollected,{PH1:s.NumberUtilities.bytesToString(t)});break}case t.FunctionCall:a&&a.url&&void 0!==a.lineNumber&&void 0!==a.columnNumber&&(i=a.url+":"+(a.lineNumber+1)+":"+(a.columnNumber+1));break;case t.JSRoot:case t.JSFrame:case t.JSIdleFrame:case t.JSSystemFrame:i=ct.frameDisplayName(a);break;case t.EventDispatch:i=a?a.type:null;break;case t.Paint:{const e=ct.quadWidth(a.clip),t=ct.quadHeight(a.clip);e&&t&&(i=nt(tt.sSDimensions,{PH1:e,PH2:t}));break}case t.ParseHTML:{const t=e.args.beginData.startLine,n=e.args.endData&&e.args.endData.endLine,r=l.ResourceUtils.displayNameForURL(e.args.beginData.url);i=n>=0?nt(tt.sSs,{PH1:r,PH2:t+1,PH3:n+1}):nt(tt.sSSquareBrackets,{PH1:r,PH2:t+1});break}case t.CompileModule:case t.CacheModule:i=l.ResourceUtils.displayNameForURL(e.args.fileName);break;case t.CompileScript:case t.CacheScript:case t.EvaluateScript:{const e=a&&a.url;e&&(i=l.ResourceUtils.displayNameForURL(e)+":"+(a.lineNumber+1));break}case t.WasmCompiledModule:case t.WasmModuleCacheHit:{const t=e.args.url;t&&(i=l.ResourceUtils.displayNameForURL(t));break}case t.StreamingCompileScript:case t.BackgroundDeserialize:case t.XHRReadyStateChange:case t.XHRLoad:{const e=a.url;e&&(i=l.ResourceUtils.displayNameForURL(e));break}case t.TimeStamp:i=a.message;break;case t.WebSocketCreate:case t.WebSocketSendHandshakeRequest:case t.WebSocketReceiveHandshakeResponse:case t.WebSocketDestroy:case t.ResourceWillSendRequest:case t.ResourceSendRequest:case t.ResourceReceivedData:case t.ResourceReceiveResponse:case t.ResourceFinish:case t.PaintImage:case t.DecodeImage:case t.ResizeImage:case t.DecodeLazyPixelRef:{const t=r.TimelineModel.EventOnTimelineData.forEvent(e).url;t&&(i=l.ResourceUtils.displayNameForURL(t));break}case t.EmbedderCallback:i=a.callbackName;break;case t.Animation:i=a&&a.name;break;case t.AsyncTask:i=a?a.name:null;break;default:i=n.TracingModel.eventHasCategory(e,r.TimelineModel.TimelineModelImpl.Category.Console)?null:await async function(){const t=r.TimelineModel.EventOnTimelineData.forEvent(e).topFrame();if(!t)return null;return t.url+":"+(t.lineNumber+1)+":"+(t.columnNumber+1)}()}return i}static async buildDetailsNodeForTraceEvent(e,t,i,a=!1){const s=r.TimelineModel.RecordType;let o,l=null;const d=e.args.data;switch(e.name){case s.GCEvent:case s.MajorGC:case s.MinorGC:case s.EventDispatch:case s.Paint:case s.Animation:case s.EmbedderCallback:case s.ParseHTML:case s.WasmStreamFromResponseCallback:case s.WasmCompiledModule:case s.WasmModuleCacheHit:case s.WasmCachedModule:case s.WasmModuleCacheInvalid:case s.WebSocketCreate:case s.WebSocketSendHandshakeRequest:case s.WebSocketReceiveHandshakeResponse:case s.WebSocketDestroy:o=await ct.buildDetailsTextForTraceEvent(e);break;case s.PaintImage:case s.DecodeImage:case s.ResizeImage:case s.DecodeLazyPixelRef:case s.XHRReadyStateChange:case s.XHRLoad:case s.ResourceWillSendRequest:case s.ResourceSendRequest:case s.ResourceReceivedData:case s.ResourceReceiveResponse:case s.ResourceFinish:{const t=r.TimelineModel.EventOnTimelineData.forEvent(e).url;if(t){const e={tabStop:!0,showColumnNumber:!1,inlineFrameIndex:0};l=m.Linkifier.Linkifier.linkifyURL(t,e)}break}case s.JSRoot:case s.FunctionCall:case s.JSIdleFrame:case s.JSSystemFrame:case s.JSFrame:{l=document.createElement("span"),c.UIUtils.createTextChild(l,ct.frameDisplayName(d));const e=this.linkifyLocation({scriptId:d.scriptId,url:d.url,lineNumber:d.lineNumber,columnNumber:d.columnNumber,target:t,isFreshRecording:a,linkifier:i});e&&(c.UIUtils.createTextChild(l," @ "),l.appendChild(e));break}case s.CompileModule:case s.CacheModule:l=this.linkifyLocation({scriptId:null,url:e.args.fileName,lineNumber:0,columnNumber:0,target:t,isFreshRecording:a,linkifier:i});break;case s.CompileScript:case s.CacheScript:case s.EvaluateScript:{const e=d.url;e&&(l=this.linkifyLocation({scriptId:null,url:e,lineNumber:d.lineNumber,columnNumber:0,target:t,isFreshRecording:a,linkifier:i}));break}case s.BackgroundDeserialize:case s.StreamingCompileScript:{const e=d.url;e&&(l=this.linkifyLocation({scriptId:null,url:e,lineNumber:0,columnNumber:0,target:t,isFreshRecording:a,linkifier:i}));break}default:n.TracingModel.eventHasCategory(e,r.TimelineModel.TimelineModelImpl.Category.Console)?o=null:l=this.linkifyTopCallFrame(e,t,i,a)}return!l&&o&&(l=document.createTextNode(o)),l}static linkifyLocation(e){const{scriptId:t,url:i,lineNumber:n,columnNumber:r,isFreshRecording:a,linkifier:s,target:o}=e,l={lineNumber:n,columnNumber:r,showColumnNumber:!0,inlineFrameIndex:0,className:"timeline-details",tabStop:!0};return a?s.linkifyScriptLocation(o,t,i,n,l):m.Linkifier.Linkifier.linkifyURL(i,l)}static linkifyTopCallFrame(e,t,i,n=!1){const a=r.TimelineProfileTree.eventStackFrame(e);if(!a)return null;const s={className:"timeline-details",tabStop:!0,inlineFrameIndex:0,showColumnNumber:!0,columnNumber:a.columnNumber,lineNumber:a.lineNumber};return n?i.maybeLinkifyConsoleCallFrame(t,a,{showColumnNumber:!0,inlineFrameIndex:0}):m.Linkifier.Linkifier.linkifyURL(a.url,s)}static buildDetailsNodeForPerformanceEvent(e){let t="https://web.dev/user-centric-performance-metrics/",i="page performance metrics";const n=r.TimelineModel.RecordType;switch(e.name){case n.MarkLCPCandidate:t="https://web.dev/lcp/",i="largest contentful paint";break;case n.MarkFCP:t="https://web.dev/first-contentful-paint/",i="first contentful paint"}return c.Fragment.html`<div>${c.XLink.XLink.create(t,nt(tt.learnMore))} about ${i}.</div>`}static buildConsumeCacheDetails(e,t){"number"==typeof e.consumedCacheSize?(t.appendTextRow(nt(tt.compilationCacheStatus),nt(tt.scriptLoadedFromCache)),t.appendTextRow(nt(tt.compilationCacheSize),s.NumberUtilities.bytesToString(e.consumedCacheSize))):"cacheRejected"in e&&e.cacheRejected?t.appendTextRow(nt(tt.compilationCacheStatus),nt(tt.failedToLoadScriptFromCache)):t.appendTextRow(nt(tt.compilationCacheStatus),nt(tt.scriptNotEligible))}static async buildTraceEventDetails(t,o,l,h,u=null){const p=o.targetByEvent(t),{duration:g,selfTime:v}=n.TracingModel.timesForEventInMilliseconds(t);let T=null;if(p){const e=p;if(void 0===t[gt]){let i=null;const a=r.TimelineModel.EventOnTimelineData.forEvent(t).url;a?i=await m.ImagePreview.ImagePreview.build(e,a,!1,{imageAltText:m.ImagePreview.ImagePreview.defaultAltTextForImageURL(a),precomputedFeatures:void 0}):t instanceof n.TracingModel.Event&&r.TimelineModel.EventOnTimelineData.forEvent(t).picture&&(i=await ct.buildPicturePreviewContent(t,e)),t[gt]=i}const i=new Set,a=r.TimelineModel.EventOnTimelineData.forEvent(t);if(a.backendNodeIds)for(let e=0;e<a.backendNodeIds.length;++e)i.add(a.backendNodeIds[e]);const s=t instanceof n.TracingModel.Event?r.TimelineModel.InvalidationTracker.invalidationEventsFor(t):null;if(s&&ct.collectInvalidationNodeIds(i,s),i.size){const t=e.model(n.DOMModel.DOMModel);t&&(T=await t.pushNodesByBackendIdsToFrontend(i))}}const f=r.TimelineModel.RecordType;let w;t.name===f.LayoutShift&&(h=!1);const y=new ft(o.targetByEvent(t),l),S=o.isMarkerEvent(t)?ct.markerStyleForEvent(t).color:ct.eventStyle(t).category.color;y.addSection(ct.eventTitle(t),S);const b=t.args.data,C=r.TimelineModel.EventOnTimelineData.forEvent(t),k=C.initiator();let P=null;if(C.warning&&y.appendWarningRow(t),t.name===f.JSFrame&&b.deoptReason&&y.appendWarningRow(t,r.TimelineModel.TimelineModelImpl.WarningType.V8Deopt),t.name===f.EventTiming&&g>e.Types.Timing.MilliSeconds(200)){if(n.TracingModel.eventIsFromNewEngine(t)||n.TracingModel.eventHasPayload(t)){const i=n.TracingModel.eventIsFromNewEngine(t)?t:t.rawPayload();e.Types.TraceEvents.isSyntheticInteractionEvent(i)&&y.appendWarningRow(t,r.TimelineModel.TimelineModelImpl.WarningType.LongInteraction)}}if(h&&!Number.isNaN(g||0)&&(y.appendTextRow(nt(tt.totalTime),i.TimeUtilities.millisToString(g||0,!0)),y.appendTextRow(nt(tt.selfTime),i.TimeUtilities.millisToString(v,!0))),o.isGenericTrace()){for(const e in t.args)try{y.appendTextRow(e,JSON.stringify(t.args[e]))}catch(i){y.appendTextRow(e,`<${typeof t.args[e]}>`)}return y.fragment}switch(t.name){case f.GCEvent:case f.MajorGC:case f.MinorGC:{const e=t.args.usedHeapSizeBefore-t.args.usedHeapSizeAfter;y.appendTextRow(nt(tt.collected),s.NumberUtilities.bytesToString(e));break}case f.JSRoot:case f.JSFrame:case f.JSIdleFrame:case f.JSSystemFrame:case f.FunctionCall:{const e=await ct.buildDetailsNodeForTraceEvent(t,o.targetByEvent(t),l,o.isFreshRecording());e&&y.appendElementRow(nt(tt.function),e);break}case f.TimerFire:case f.TimerInstall:case f.TimerRemove:y.appendTextRow(nt(tt.timerId),b.timerId),t.name===f.TimerInstall&&(y.appendTextRow(nt(tt.timeout),i.TimeUtilities.millisToString(b.timeout)),y.appendTextRow(nt(tt.repeats),!b.singleShot));break;case f.FireAnimationFrame:y.appendTextRow(nt(tt.callbackId),b.id);break;case f.ResourceWillSendRequest:case f.ResourceSendRequest:case f.ResourceReceiveResponse:case f.ResourceReceivedData:case f.ResourceFinish:if(P=C.url,P){const e={tabStop:!0,showColumnNumber:!1,inlineFrameIndex:0};y.appendElementRow(nt(tt.resource),m.Linkifier.Linkifier.linkifyURL(P,e))}if(b.requestMethod&&y.appendTextRow(nt(tt.requestMethod),b.requestMethod),"number"==typeof b.statusCode&&y.appendTextRow(nt(tt.statusCode),b.statusCode),b.mimeType&&y.appendTextRow(nt(tt.mimeTypeCaps),b.mimeType),"priority"in b){const e=d.NetworkPriorities.uiLabelForNetworkPriority(b.priority);y.appendTextRow(nt(tt.priority),e)}b.encodedDataLength&&y.appendTextRow(nt(tt.encodedData),nt(tt.sBytes,{n:b.encodedDataLength})),b.decodedBodyLength&&y.appendTextRow(nt(tt.decodedBody),nt(tt.sBytes,{n:b.decodedBodyLength}));break;case f.CompileModule:y.appendLocationRow(nt(tt.module),t.args.fileName,0);break;case f.CompileScript:{P=b&&b.url,P&&y.appendLocationRow(nt(tt.script),P,b.lineNumber,b.columnNumber);(b.eager??!1)&&y.appendTextRow(nt(tt.eagerCompile),!0);const e=b.streamed;y.appendTextRow(nt(tt.streamed),e+(e?"":`: ${b.notStreamedReason}`)),ct.buildConsumeCacheDetails(b,y);break}case f.CacheModule:P=b&&b.url,y.appendTextRow(nt(tt.compilationCacheSize),s.NumberUtilities.bytesToString(b.producedCacheSize));break;case f.CacheScript:P=b&&b.url,P&&y.appendLocationRow(nt(tt.script),P,b.lineNumber,b.columnNumber),y.appendTextRow(nt(tt.compilationCacheSize),s.NumberUtilities.bytesToString(b.producedCacheSize));break;case f.EvaluateScript:P=b&&b.url,P&&y.appendLocationRow(nt(tt.script),P,b.lineNumber,b.columnNumber);break;case f.WasmStreamFromResponseCallback:case f.WasmCompiledModule:case f.WasmCachedModule:case f.WasmModuleCacheHit:case f.WasmModuleCacheInvalid:if(b){P=t.args.url,P&&y.appendTextRow(nt(tt.url),P);const e=t.args.producedCachedSize;e&&y.appendTextRow(nt(tt.producedCacheSize),e);const i=t.args.consumedCachedSize;i&&y.appendTextRow(nt(tt.consumedCacheSize),i)}break;case f.Paint:{const e=b.clip;y.appendTextRow(nt(tt.location),nt(tt.sSCurlyBrackets,{PH1:e[0],PH2:e[1]}));const t=ct.quadWidth(e),i=ct.quadHeight(e);y.appendTextRow(nt(tt.dimensions),nt(tt.sSDimensions,{PH1:t,PH2:i}))}case f.PaintSetup:case f.Rasterize:case f.ScrollLayer:w=nt(tt.layerRoot);break;case f.PaintImage:case f.DecodeLazyPixelRef:case f.DecodeImage:case f.ResizeImage:case f.DrawLazyPixelRef:if(w=nt(tt.ownerElement),P=C.url,P){const e={tabStop:!0,showColumnNumber:!1,inlineFrameIndex:0};y.appendElementRow(nt(tt.imageUrl),m.Linkifier.Linkifier.linkifyURL(P,e))}break;case f.ParseAuthorStyleSheet:if(P=b.styleSheetUrl,P){const e={tabStop:!0,showColumnNumber:!1,inlineFrameIndex:0};y.appendElementRow(nt(tt.stylesheetUrl),m.Linkifier.Linkifier.linkifyURL(P,e))}break;case f.UpdateLayoutTree:case f.RecalculateStyles:y.appendTextRow(nt(tt.elementsAffected),t.args.elementCount);break;case f.Layout:{const e=t.args.beginData;y.appendTextRow(nt(tt.nodesThatNeedLayout),nt(tt.sOfS,{PH1:e.dirtyObjects,PH2:e.totalObjects})),w=nt(tt.layoutRoot);break}case f.ConsoleTime:y.appendTextRow(nt(tt.message),t.name);break;case f.WebSocketCreate:case f.WebSocketSendHandshakeRequest:case f.WebSocketReceiveHandshakeResponse:case f.WebSocketDestroy:{const e=k?k.args.data:b;void 0!==e.webSocketURL&&y.appendTextRow(i.i18n.lockedString("URL"),e.webSocketURL),void 0!==e.webSocketProtocol&&y.appendTextRow(nt(tt.websocketProtocol),e.webSocketProtocol),void 0!==b.message&&y.appendTextRow(nt(tt.message),b.message);break}case f.EmbedderCallback:y.appendTextRow(nt(tt.callbackFunction),b.callbackName);break;case f.Animation:"n"===n.TracingModel.phaseForEvent(t)&&y.appendTextRow(nt(tt.state),b.state);break;case f.ParseHTML:{const e=t.args.beginData,i=e.startLine-1,n=t.args.endData?t.args.endData.endLine-1:void 0;P=e.url,P&&y.appendLocationRange(nt(tt.range),P,i,n);break}case f.FireIdleCallback:y.appendTextRow(nt(tt.allottedTime),i.TimeUtilities.millisToString(b.allottedMilliseconds)),y.appendTextRow(nt(tt.invokedByTimeout),b.timedOut);case f.RequestIdleCallback:case f.CancelIdleCallback:y.appendTextRow(nt(tt.callbackId),b.id);break;case f.EventDispatch:y.appendTextRow(nt(tt.type),b.type);break;case f.MarkLCPCandidate:y.appendTextRow(nt(tt.type),String(b.type)),y.appendTextRow(nt(tt.size),String(b.size));case f.MarkFirstPaint:case f.MarkFCP:case f.MarkLoad:case f.MarkDOMContent:{const e=yt(t,o,u);y.appendTextRow(nt(tt.timestamp),i.TimeUtilities.preciseMillisToString(e,1)),y.appendElementRow(nt(tt.details),ct.buildDetailsNodeForPerformanceEvent(t));break}case f.EventTiming:{const i=await ct.buildDetailsNodeForTraceEvent(t,o.targetByEvent(t),l,o.isFreshRecording());i&&y.appendElementRow(nt(tt.details),i);let r=null;n.TracingModel.eventIsFromNewEngine(t)?r=t:n.TracingModel.eventHasPayload(t)&&(r=t.rawPayload()),r&&e.Types.TraceEvents.isSyntheticInteractionEvent(r)&&y.appendTextRow(nt(tt.interactionID),r.interactionId);break}case f.LayoutShift:{if(!n.TracingModel.eventIsFromNewEngine(t)||!e.Types.TraceEvents.isSyntheticLayoutShift(t)){console.error("Unexpected type for LayoutShift event");break}const r=t,s=r.args.data,o=document.createElement("span"),l=c.XLink.XLink.create("https://web.dev/cls/",nt(tt.cumulativeLayoutShifts)),d=c.XLink.XLink.create("https://web.dev/evolving-cls/",nt(tt.evolvedClsLink));if(o.appendChild(i.i18n.getFormatLocalizedString(it,tt.sCLSInformation,{PH1:l,PH2:d})),y.appendElementRow(nt(tt.warning),o,!0),!s)break;y.appendTextRow(nt(tt.score),s.score.toPrecision(4)),y.appendTextRow(nt(tt.cumulativeScore),s.cumulative_score.toPrecision(4)),y.appendTextRow(nt(tt.currentClusterId),r.parsedData.sessionWindowData.id),y.appendTextRow(nt(tt.currentClusterScore),r.parsedData.sessionWindowData.cumulativeWindowScore.toPrecision(4)),y.appendTextRow(nt(tt.hadRecentInput),b.had_recent_input?nt(tt.yes):nt(tt.no));for(const e of b.impacted_nodes){const t=new E(e.old_rect),i=new E(e.new_rect),n=await a.Linkifier.Linkifier.linkify(t),r=await a.Linkifier.Linkifier.linkify(i);y.appendElementRow(nt(tt.movedFrom),n),y.appendElementRow(nt(tt.movedTo),r)}break}default:{const e=await ct.buildDetailsNodeForTraceEvent(t,o.targetByEvent(t),l,o.isFreshRecording());e&&y.appendElementRow(nt(tt.details),e);break}}for(let e=0;e<C.backendNodeIds.length;++e){const t=T&&T.get(C.backendNodeIds[e]);if(t){const e=await a.Linkifier.Linkifier.linkify(t);y.appendElementRow(w||nt(tt.relatedNode),e)}}t[gt]&&(y.addSection(nt(tt.preview)),y.appendElementRow("",t[gt])),(k||C.stackTraceForSelfOrInitiator()||r.TimelineModel.InvalidationTracker.invalidationEventsFor(t))&&ct.generateCauses(t,o.targetByEvent(t),T,y);const M={};if(h&&ct.aggregatedStatsForTraceEvent(M,o,t)){y.addSection(nt(tt.aggregatedTime));const e=ct.generatePieChart(M,ct.eventStyle(t).category,v);y.appendElementRow("",e)}return y.fragment}static statsForTimeRange(e,t,i){if(!e.length)return{idle:i-t};!function(e){if(e[wt])return;const t={},i=[];let a=0;function s(e,i){let n=t[e];if(n||(n={time:[],value:[]},t[e]=n),n.time.length&&n.time[n.time.length-1]===i||a>i)return;const r=n.value.length>0?n.value[n.value.length-1]:0;n.value.push(r+i-a),n.time.push(i)}function o(e,t,i){e&&s(e,i),a=i,t&&s(t,i)}r.TimelineModel.TimelineModelImpl.forEachEvent(e,(function(e){const{startTime:t}=n.TracingModel.timesForEventInMilliseconds(e),r=ct.eventStyle(e).category.name,a=i.length?i[i.length-1]:null;r!==a&&o(a||null,r,t),i.push(r)}),(function(e){const{endTime:t}=n.TracingModel.timesForEventInMilliseconds(e),r=i.pop(),a=i.length?i[i.length-1]:null;r!==a&&o(r||null,a||null,t||0)}),void 0,void 0,void 0,function(){const e=ct.visibleEventsFilter();return t=>e.accept(t)||n.TracingModel.TracingModel.isTopLevelEvent(t)}());e[wt]=t}(e);const a=function(e,t){const i=Object.assign({},e);for(const e in t)i[e]-=t[e];return i}(l(i),l(t)),o=Object.values(a).reduce(((e,t)=>e+t),0);return a.idle=Math.max(0,i-t-o),a;function l(t){const i={},n=e[wt];for(const e in n){const r=n[e],a=s.ArrayUtilities.upperBound(r.time,t,s.ArrayUtilities.DEFAULT_COMPARATOR);let o;if(0===a)o=0;else if(a===r.time.length)o=r.value[r.value.length-1];else{const e=r.time[a-1],i=r.time[a],n=r.value[a-1];o=n+(r.value[a]-n)*(t-e)/(i-e)}i[e]=o}return i}}static async buildNetworkRequestDetails(e,t,n){const a=t.targetByEvent(e.children[0]),o=new ft(a,n),l=ct.networkRequestCategory(e),c=ct.networkCategoryColor(l);if(o.addSection(nt(tt.networkRequest),c),e.url){const t={tabStop:!0,showColumnNumber:!1,inlineFrameIndex:0};o.appendElementRow(i.i18n.lockedString("URL"),m.Linkifier.Linkifier.linkifyURL(e.url,t))}const h=e.endTime-(e.getStartTime()||-1/0);if(isFinite(h)){let t=i.TimeUtilities.millisToString(h,!0);const n=(e.finishTime||e.getStartTime())-e.getStartTime(),r=e.endTime-(e.finishTime||0);if(isFinite(n)&&isFinite(r)){const a=i.TimeUtilities.millisToString(n,!0),s=i.TimeUtilities.millisToString(r,!0),o=e.cached()?nt(tt.loadFromCache):nt(tt.networkTransfer);t+=nt(tt.SSSResourceLoading,{PH1:a,PH2:o,PH3:s})}o.appendTextRow(nt(tt.duration),t)}if(e.requestMethod&&o.appendTextRow(nt(tt.requestMethod),e.requestMethod),"string"==typeof e.priority){const t=d.NetworkPriorities.uiLabelForNetworkPriority(e.priority);o.appendTextRow(nt(tt.priority),t)}e.mimeType&&o.appendTextRow(nt(tt.mimeType),e.mimeType);let u="";e.memoryCached()?u+=nt(tt.FromMemoryCache):e.cached()?u+=nt(tt.FromCache):e.timing&&e.timing.pushStart&&(u+=nt(tt.FromPush)),e.fromServiceWorker&&(u+=nt(tt.FromServiceWorker)),!e.encodedDataLength&&u||(u=`${s.NumberUtilities.bytesToString(e.encodedDataLength)}${u}`),o.appendTextRow(nt(tt.encodedData),u),e.decodedBodyLength&&o.appendTextRow(nt(tt.decodedBody),s.NumberUtilities.bytesToString(e.decodedBodyLength));const p=nt(tt.initiator),g=e.children[0],v=r.TimelineModel.EventOnTimelineData.forEvent(g).topFrame();if(v){const e=n.maybeLinkifyConsoleCallFrame(a,v,{tabStop:!0,inlineFrameIndex:0,showColumnNumber:!0});e&&o.appendElementRow(p,e)}else{const e=r.TimelineModel.EventOnTimelineData.forEvent(g).initiator();if(e){const t=r.TimelineModel.EventOnTimelineData.forEvent(e).url;if(t){const e=n.maybeLinkifyScriptLocation(a,null,t,0,{tabStop:!0,inlineFrameIndex:0});e&&o.appendElementRow(p,e)}}}if(!dt.get(e)&&e.url&&a){const t=await m.ImagePreview.ImagePreview.build(a,e.url,!1,{imageAltText:m.ImagePreview.ImagePreview.defaultAltTextForImageURL(e.url),precomputedFeatures:void 0});dt.set(e,t)}const T=dt.get(e);return T&&o.appendElementRow(nt(tt.preview),T),o.fragment}static stackTraceFromCallFrames(e){return{callFrames:e}}static generateCauses(e,t,a,s){const o=r.TimelineModel.RecordType,{startTime:l}=n.TracingModel.timesForEventInMilliseconds(e);let d,h;switch(e.name){case o.TimerFire:d=nt(tt.timerInstalled);break;case o.FireAnimationFrame:d=nt(tt.animationFrameRequested);break;case o.FireIdleCallback:d=nt(tt.idleCallbackRequested);break;case o.UpdateLayoutTree:case o.RecalculateStyles:h=nt(tt.recalculationForced);break;case o.Layout:d=nt(tt.firstLayoutInvalidation),h=nt(tt.layoutForced)}const m=r.TimelineModel.EventOnTimelineData.forEvent(e);m.stackTrace&&m.stackTrace.length&&(s.addSection(nt(tt.callStacks)),s.appendStackTrace(h||nt(tt.stackTrace),ct.stackTraceFromCallFrames(m.stackTrace)));const u=r.TimelineModel.EventOnTimelineData.forEvent(e).initiator();if(e instanceof n.TracingModel.Event&&r.TimelineModel.InvalidationTracker.invalidationEventsFor(e)&&t)s.addSection(nt(tt.invalidations)),ct.generateInvalidations(e,t,a,s);else if(u){const e=l-u.startTime;s.appendTextRow(nt(tt.pendingFor),i.TimeUtilities.preciseMillisToString(e,1));const t=document.createElement("span");t.classList.add("devtools-link"),c.ARIAUtils.markAsLink(t),t.tabIndex=0,t.textContent=nt(tt.reveal),t.addEventListener("click",(()=>{Ve.instance().select(De.fromTraceEvent(u))})),t.addEventListener("keydown",(e=>{"Enter"===e.key&&(Ve.instance().select(De.fromTraceEvent(u)),e.consume(!0))})),s.appendElementRow(nt(tt.initiator),t);const n=r.TimelineModel.EventOnTimelineData.forEvent(u).stackTrace;n&&s.appendStackTrace(d||nt(tt.firstInvalidated),ct.stackTraceFromCallFrames(n))}}static generateInvalidations(e,t,i,n){const a=r.TimelineModel.InvalidationTracker.invalidationEventsFor(e);if(!a)return;const s={};for(const e of a)s[e.type]||(s[e.type]=[]),s[e.type].push(e);Object.keys(s).forEach((function(e){ct.generateInvalidationsForType(e,t,s[e],i,n)}))}static generateInvalidationsForType(e,t,i,n,a){let s;switch(e){case r.TimelineModel.RecordType.StyleRecalcInvalidationTracking:s=nt(tt.styleInvalidations);break;case r.TimelineModel.RecordType.LayoutInvalidationTracking:s=nt(tt.layoutInvalidations);break;default:s=nt(tt.otherInvalidations)}const o=new c.TreeOutline.TreeOutlineInShadow;o.registerCSSFiles([F]),o.element.classList.add("invalidations-tree");const l=function(e){const t=new Map;for(let i=0;i<e.length;i++){const n=e[i];let r="";n.cause.reason&&(r+=n.cause.reason+"."),n.cause.stackTrace&&n.cause.stackTrace.forEach((function(e){r+=e.functionName+".",r+=e.scriptId+".",r+=e.url+".",r+=e.lineNumber+".",r+=e.columnNumber+"."}));const a=t.get(r);a?a.push(n):t.set(r,[n])}return[...t.values()]}(i);l.forEach((function(e){const i=new pt(t,n,a,e);o.appendChild(i)})),a.appendElementRow(s,o.element,!1,!0)}static collectInvalidationNodeIds(e,t){s.SetUtilities.addAll(e,t.map((e=>e.nodeId)).filter((e=>e)))}static aggregatedStatsForTraceEvent(t,i,r){const a=i.inspectedTargetEvents(),{startTime:o,endTime:l}=n.TracingModel.timesForEventInMilliseconds(r);const d=s.ArrayUtilities.binaryIndexOf(a,o,(function(e,t){return e-t.startTime}));if(d<0)return!1;let c=!1;if(l)for(let e=d;e<a.length;e++){const i=a[e];if(i.startTime>=l)break;if(!i.selfTime)continue;if(n.TracingModel.threadIDForEvent(i)!==n.TracingModel.threadIDForEvent(r))continue;e>d&&(c=!0);const s=ct.eventStyle(i).category.name;t[s]=(t[s]||0)+i.selfTime}if(e.Types.TraceEvents.isAsyncPhase(n.TracingModel.phaseForEvent(r))){if(l){let e=0;for(const i in t)e+=t[i];t.idle=Math.max(0,l-o-e)}return!1}return c}static async buildPicturePreviewContent(e,t){const i=await new r.TimelineFrameModel.LayerPaintEvent(e,t).snapshotPromise();if(!i)return null;const n=i.snapshot.replay();i.snapshot.release();const a=await n;if(!a)return null;const s=document.createElement("div"),o=s.attachShadow({mode:"open"});o.adoptedStyleSheets=[D];const l=o.createChild("div");l.classList.add("image-preview-container","vbox","link");const d=l.createChild("img");d.src=a,d.alt=m.ImagePreview.ImagePreview.defaultAltTextForImageURL(a);return l.createChild("a").textContent=nt(tt.paintProfiler),c.ARIAUtils.markAsLink(l),l.tabIndex=0,l.addEventListener("click",(()=>Ve.instance().select(De.fromTraceEvent(e))),!1),l.addEventListener("keydown",(t=>{"Enter"===t.key&&(Ve.instance().select(De.fromTraceEvent(e)),t.consume(!0))})),s}static createEventDivider(e,t){const n=document.createElement("div");n.classList.add("resources-event-divider");const r=i.TimeUtilities.millisToString(e.startTime-t);c.Tooltip.Tooltip.install(n,nt(tt.sAtS,{PH1:ct.eventTitle(e),PH2:r}));const a=ct.markerStyleForEvent(e);return a.tall&&(n.style.backgroundColor=a.color),n}static visibleTypes(){const e=ct.initEventStyles(),t=[];for(const i in e)e[i].hidden||t.push(i);return t}static visibleEventsFilter(){return new r.TimelineModelFilter.TimelineVisibleEventsFilter(ct.visibleTypes())}static categories(){return at||(at={loading:new Tt("loading",nt(tt.loading),!0,"hsl(214, 67%, 74%)","hsl(214, 67%, 66%)"),experience:new Tt("experience",nt(tt.experience),!1,"hsl(5, 80%, 74%)","hsl(5, 80%, 66%)"),scripting:new Tt("scripting",nt(tt.scripting),!0,"hsl(43, 83%, 72%)","hsl(43, 83%, 64%) "),rendering:new Tt("rendering",nt(tt.rendering),!0,"hsl(256, 67%, 76%)","hsl(256, 67%, 70%)"),painting:new Tt("painting",nt(tt.painting),!0,"hsl(109, 33%, 64%)","hsl(109, 33%, 55%)"),gpu:new Tt("gpu",nt(tt.gpu),!1,"hsl(109, 33%, 64%)","hsl(109, 33%, 55%)"),async:new Tt("async",nt(tt.async),!1,"hsl(0, 100%, 50%)","hsl(0, 100%, 40%)"),other:new Tt("other",nt(tt.system),!1,"hsl(0, 0%, 87%)","hsl(0, 0%, 79%)"),idle:new Tt("idle",nt(tt.idle),!1,"hsl(0, 0%, 98%)","hsl(0, 0%, 98%)")},at)}static setCategories(e){at=e}static getTimelineMainEventCategories(){return st||(st=["idle","loading","painting","rendering","scripting","other"],st)}static setTimelineMainEventCategories(e){st=e}static generatePieChart(e,t,n){let r=0;for(const t in e)r+=e[t];const a=document.createElement("div");a.classList.add("timeline-details-view-pie-chart-wrapper"),a.classList.add("hbox");const s=new d.PieChart.PieChart,o=[];function l(e,t,i,n){i&&o.push({value:i,color:n,title:t})}if(t){n&&l(t.name,nt(tt.sSelf,{PH1:t.title}),n,t.color);const i=e[t.name]-(n||0);i>0&&l(t.name,nt(tt.sChildren,{PH1:t.title}),i,t.childColor)}for(const i in ct.categories()){const n=ct.categories()[i];n!==t&&l(n.name,n.title,e[n.name],n.childColor)}s.data={chartName:nt(tt.timeSpentInRendering),size:110,formatter:e=>i.TimeUtilities.preciseMillisToString(e),showLegend:!0,total:r,slices:o};return a.createChild("div","vbox").appendChild(s),a}static generateDetailsContentForFrame(e,t){const n=new ft(null,null);n.addSection(nt(tt.frame));const r=ct.frameDuration(e);if(n.appendElementRow(nt(tt.duration),r,e.hasWarnings()),n.appendTextRow(nt(tt.cpuTime),i.TimeUtilities.millisToString(e.cpuTime,!0)),t){const e=document.createElement("div");e.classList.add("timeline-filmstrip-preview"),t.imageDataPromise().then((e=>c.UIUtils.loadImageFromData(e))).then((t=>t&&e.appendChild(t))),n.appendElementRow("",e),e.addEventListener("click",function(e){new d.FilmStripView.Dialog(e,0)}.bind(null,t),!1)}return e.layerTree&&n.appendElementRow(nt(tt.layerTree),m.Linkifier.Linkifier.linkifyRevealable(e.layerTree,nt(tt.show))),n.fragment}static frameDuration(e){const t=nt(tt.sAtSParentheses,{PH1:i.TimeUtilities.millisToString(e.endTime-e.startTime,!0),PH2:i.TimeUtilities.millisToString(e.startTimeOffset,!0)});if(!e.hasWarnings())return i.i18n.getFormatLocalizedString(it,tt.emptyPlaceholder,{PH1:t});const n=c.XLink.XLink.create("https://developers.google.com/web/fundamentals/performance/rendering/",nt(tt.jank));return i.i18n.getFormatLocalizedString(it,tt.sLongFrameTimesAreAnIndicationOf,{PH1:t,PH2:n})}static quadWidth(e){return Math.round(Math.sqrt(Math.pow(e[0]-e[2],2)+Math.pow(e[1]-e[3],2)))}static quadHeight(e){return Math.round(Math.sqrt(Math.pow(e[0]-e[6],2)+Math.pow(e[1]-e[7],2)))}static eventDispatchDesciptors(){if(ot)return ot;const e="hsl(40,100%,80%)",t="hsl(40,100%,50%)";return ot=[new vt(1,e,["mousemove","mouseenter","mouseleave","mouseout","mouseover"]),new vt(1,e,["pointerover","pointerout","pointerenter","pointerleave","pointermove"]),new vt(2,"hsl(90,100%,40%)",["wheel"]),new vt(3,t,["click","mousedown","mouseup"]),new vt(3,t,["touchstart","touchend","touchmove","touchcancel"]),new vt(3,t,["pointerdown","pointerup","pointercancel","gotpointercapture","lostpointercapture"]),new vt(3,"hsl(256,100%,75%)",["keydown","keyup","keypress"])],ot}static markerShortTitle(e){const t=r.TimelineModel.RecordType;switch(e.name){case t.MarkDOMContent:return i.i18n.lockedString("DCL");case t.MarkLoad:return i.i18n.lockedString("L");case t.MarkFirstPaint:return i.i18n.lockedString("FP");case t.MarkFCP:return i.i18n.lockedString("FCP");case t.MarkLCPCandidate:return i.i18n.lockedString("LCP")}return null}static markerStyleForEvent(e){const t=[6,4],i=ct.eventTitle(e),a=r.TimelineModel.RecordType;if(e.name!==a.NavigationStart&&(n.TracingModel.eventHasCategory(e,r.TimelineModel.TimelineModelImpl.Category.Console)||n.TracingModel.eventHasCategory(e,r.TimelineModel.TimelineModelImpl.Category.UserTiming)))return{title:i,dashStyle:t,lineWidth:.5,color:n.TracingModel.eventHasCategory(e,r.TimelineModel.TimelineModelImpl.Category.UserTiming)?"purple":"orange",tall:!1,lowPriority:!1};let s=!1,o="grey";switch(e.name){case a.NavigationStart:o="#FF9800",s=!0;break;case a.FrameStartedLoading:o="green",s=!0;break;case a.MarkDOMContent:o="#0867CB",s=!0;break;case a.MarkLoad:o="#B31412",s=!0;break;case a.MarkFirstPaint:o="#228847",s=!0;break;case a.MarkFCP:o="#1A6937",s=!0;break;case a.MarkLCPCandidate:o="#1A3422",s=!0;break;case a.TimeStamp:o="orange"}return{title:i,dashStyle:t,lineWidth:.5,color:o,tall:s,lowPriority:!1}}static colorForId(e){return lt||(lt=new a.Color.Generator({min:30,max:330,count:void 0},{min:50,max:80,count:3},85),lt.setColorForID("","#f2ecdc")),lt.colorForID(e)}static eventWarning(e,t){const a=e instanceof n.TracingModel.Event?r.TimelineModel.EventOnTimelineData.forEvent(e):null,{duration:s}=n.TracingModel.timesForEventInMilliseconds(e),o=t||a?.warning;if(!o)return null;const l=r.TimelineModel.TimelineModelImpl.WarningType,d=document.createElement("span"),h=e.args.data;switch(o){case l.ForcedStyle:case l.ForcedLayout:{const e=c.XLink.XLink.create("https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing#avoid-forced-synchronous-layouts",nt(tt.forcedReflow));d.appendChild(i.i18n.getFormatLocalizedString(it,tt.sIsALikelyPerformanceBottleneck,{PH1:e}));break}case l.IdleDeadlineExceeded:{const e=i.TimeUtilities.millisToString((s||0)-h.allottedMilliseconds,!0);d.textContent=nt(tt.idleCallbackExecutionExtended,{PH1:e});break}case l.LongHandler:d.textContent=nt(tt.handlerTookS,{PH1:i.TimeUtilities.millisToString(s||0,!0)});break;case l.LongInteraction:{const e=c.XLink.XLink.create("https://web.dev/inp",nt(tt.longInteractionINP));d.appendChild(i.i18n.getFormatLocalizedString(it,tt.sIsLikelyPoorPageResponsiveness,{PH1:e}));break}case l.LongRecurringHandler:d.textContent=nt(tt.recurringHandlerTookS,{PH1:i.TimeUtilities.millisToString(s||0,!0)});break;case l.LongTask:{const e=c.XLink.XLink.create("https://web.dev/optimize-long-tasks/",nt(tt.longTask));d.appendChild(i.i18n.getFormatLocalizedString(it,tt.sTookS,{PH1:e,PH2:i.TimeUtilities.millisToString(s||0,!0)}));break}case l.V8Deopt:d.appendChild(c.XLink.XLink.create("https://github.com/GoogleChrome/devtools-docs/issues/53",nt(tt.notOptimized))),c.UIUtils.createTextChild(d,nt(tt.emptyPlaceholderColon,{PH1:h.deoptReason}));break;default:console.assert(!1,"Unhandled TimelineModel.WarningType")}return d}static displayNameForFrame(e,t=30){return t||(t=30),e.url.startsWith("about:")?`"${s.StringUtilities.trimMiddle(e.name,t)}"`:e.url.trimEnd(t)}}class ht{title;category;hidden;constructor(e,t,i=!1){this.title=e,this.category=t,this.hidden=i}}var mt;!function(e){e.HTML="HTML",e.Script="Script",e.Style="Style",e.Media="Media",e.Other="Other"}(mt||(mt={}));const ut=Symbol("aggregatedStats");class pt extends c.TreeOutline.TreeElement{toggleOnClick;relatedNodesMap;contentHelper;invalidations;constructor(e,t,i,n){super("",!0),this.listItemElement.classList.add("header"),this.selectable=!1,this.toggleOnClick=!0,this.relatedNodesMap=t,this.contentHelper=i,this.invalidations=n,this.title=this.createTitle(e)}createTitle(e){const t=this.invalidations[0],n=t.cause.reason||nt(tt.unknownCause),r=t.cause.stackTrace&&t.cause.stackTrace[0],a=this.getTruncatedNodesElement(this.invalidations);if(null===a)return i.i18n.getFormatLocalizedString(it,tt.emptyPlaceholder,{PH1:n});const s=i.i18n.getFormatLocalizedString(it,tt.sForS,{PH1:n,PH2:a});if(r&&this.contentHelper.linkifier()){const t=document.createElement("span");t.classList.add("monospace");const n=i.i18n.getFormatLocalizedString(it,tt.sSDot,{PH1:s,PH2:t});t.createChild("span").textContent=ct.frameDisplayName(r);const a=this.contentHelper.linkifier();if(a){const i=a.maybeLinkifyConsoleCallFrame(e,r,{showColumnNumber:!0,inlineFrameIndex:0});i&&(i.textContent||(i.textContent=nt(tt.unknown)),t.createChild("span").textContent=" @ ",t.createChild("span").appendChild(i))}return n}return s}async onpopulate(){const e=document.createElement("div");e.classList.add("content");const t=this.invalidations[0];if(t.cause.stackTrace){const i=e.createChild("div");c.UIUtils.createTextChild(i,nt(tt.stackTraceColon)),this.contentHelper.createChildStackTraceElement(i,ct.stackTraceFromCallFrames(t.cause.stackTrace))}c.UIUtils.createTextChild(e,1!==this.invalidations.length?nt(tt.nodes):nt(tt.node));const i=e.createChild("div","node-list");let n=!0;for(let e=0;e<this.invalidations.length;e++){const t=this.invalidations[e],r=this.createInvalidationNode(t,!0);if(r){n||c.UIUtils.createTextChild(i,", "),n=!1,i.appendChild(r);const e=t.extraData?", "+t.extraData:"";t.changedId?c.UIUtils.createTextChild(i,nt(tt.changedIdToSs,{PH1:t.changedId,PH2:e})):t.changedClass?c.UIUtils.createTextChild(i,nt(tt.changedClassToSs,{PH1:t.changedClass,PH2:e})):t.changedAttribute?c.UIUtils.createTextChild(i,nt(tt.changedAttributeToSs,{PH1:t.changedAttribute,PH2:e})):t.changedPseudo?c.UIUtils.createTextChild(i,nt(tt.changedPesudoToSs,{PH1:t.changedPseudo,PH2:e})):t.selectorPart&&c.UIUtils.createTextChild(i,nt(tt.changedSs,{PH1:t.selectorPart,extraData:e}))}}const r=new c.TreeOutline.TreeElement(e,!1);r.selectable=!1,this.appendChild(r)}getTruncatedNodesElement(e){const t=[],n={};for(let i=0;i<e.length;i++){const r=e[i],a=this.createInvalidationNode(r,!1);a.addEventListener("click",(e=>e.consume()),!1),a&&r.nodeId&&!n[r.nodeId]&&(t.push(a),n[r.nodeId]=!0)}if(1===t.length){const e=t[0];return e instanceof HTMLSpanElement?e:null}return 2===t.length?i.i18n.getFormatLocalizedString(it,tt.sAndS,{PH1:t[0],PH2:t[1]}):3===t.length?i.i18n.getFormatLocalizedString(it,tt.sAndSOther,{PH1:t[0],PH2:t[1]}):t.length>=4?i.i18n.getFormatLocalizedString(it,tt.sSAndSOthers,{PH1:t[0],PH2:t[1],PH3:String(t.length-2)}):null}createInvalidationNode(e,t){const i=e.nodeId&&this.relatedNodesMap?this.relatedNodesMap.get(e.nodeId):null;if(i){const e=document.createElement("span");return a.Linkifier.Linkifier.linkify(i).then((t=>e.appendChild(t))),e}if(e.nodeName){const t=document.createElement("span");return t.textContent=e.nodeName,t}if(t){const e=document.createElement("span");return c.UIUtils.createTextChild(e,nt(tt.UnknownNode))}throw new Error("Unable to create invalidation node")}}const gt=Symbol("previewElement");class vt{priority;color;eventTypes;constructor(e,t,i){this.priority=e,this.color=t,this.eventTypes=i}}class Tt{name;title;visible;childColor;color;hiddenInternal;constructor(e,t,i,n,r){this.name=e,this.title=t,this.visible=i,this.childColor=n,this.color=r,this.hidden=!1}get hidden(){return Boolean(this.hiddenInternal)}set hidden(e){this.hiddenInternal=e}}class ft{fragment;linkifierInternal;target;element;tableElement;constructor(e,t){this.fragment=document.createDocumentFragment(),this.linkifierInternal=t,this.target=e,this.element=document.createElement("div"),this.element.classList.add("timeline-details-view-block"),this.tableElement=this.element.createChild("div","vbox timeline-details-chip-body"),this.fragment.appendChild(this.element)}addSection(e,t){if(this.tableElement.hasChildNodes()?(this.element=document.createElement("div"),this.element.classList.add("timeline-details-view-block"),this.fragment.appendChild(this.element)):this.element.removeChildren(),e){const i=this.element.createChild("div","timeline-details-chip-title");t&&(i.createChild("div").style.backgroundColor=t),c.UIUtils.createTextChild(i,e)}this.tableElement=this.element.createChild("div","vbox timeline-details-chip-body"),this.fragment.appendChild(this.element)}linkifier(){return this.linkifierInternal}appendTextRow(e,t){const i=this.tableElement.createChild("div","timeline-details-view-row");i.createChild("div","timeline-details-view-row-title").textContent=e,i.createChild("div","timeline-details-view-row-value").textContent=t.toString()}appendElementRow(e,t,i,n){const r=this.tableElement.createChild("div","timeline-details-view-row");i&&r.classList.add("timeline-details-warning"),n&&r.classList.add("timeline-details-stack-values");r.createChild("div","timeline-details-view-row-title").textContent=e;const a=r.createChild("div","timeline-details-view-row-value");t instanceof Node?a.appendChild(t):c.UIUtils.createTextChild(a,t||"")}appendLocationRow(e,t,i,n){if(!this.linkifierInternal||!this.target)return;const r={tabStop:!0,columnNumber:n,showColumnNumber:!0,inlineFrameIndex:0},a=this.linkifierInternal.maybeLinkifyScriptLocation(this.target,null,t,i,r);a&&this.appendElementRow(e,a)}appendLocationRange(e,t,i,n){if(!this.linkifierInternal||!this.target)return;const r=document.createElement("span"),a=this.linkifierInternal.maybeLinkifyScriptLocation(this.target,null,t,i,{tabStop:!0,inlineFrameIndex:0});a&&(r.appendChild(a),c.UIUtils.createTextChild(r,s.StringUtilities.sprintf(" [%s…%s]",i+1,(n||0)+1||"")),this.appendElementRow(e,r))}appendStackTrace(e,t){if(!this.linkifierInternal||!this.target)return;const i=this.tableElement.createChild("div","timeline-details-view-row");i.createChild("div","timeline-details-view-row-title").textContent=e,this.createChildStackTraceElement(i,t)}createChildStackTraceElement(e,t){if(!this.linkifierInternal||!this.target)return;e.classList.add("timeline-details-stack-values");const i=e.createChild("div","timeline-details-view-row-value timeline-details-view-row-stack-trace"),n=m.JSPresentationUtils.buildStackTracePreviewContents(this.target,this.linkifierInternal,{stackTrace:t,tabStops:!0});i.appendChild(n.element)}appendWarningRow(e,t){const i=ct.eventWarning(e,t);i&&this.appendElementRow(nt(tt.warning),i,!0)}}const wt=Symbol("categoryBreakdownCache");function yt(t,i,r){const{startTime:a}=n.TracingModel.timesForEventInMilliseconds(t);if(n.TracingModel.eventIsFromNewEngine(t)&&r){const i=e.Helpers.Timing.timeStampForEventAdjustedByClosestNavigation(t,r.Meta.traceBounds,r.Meta.navigationsByNavigationId,r.Meta.navigationsByFrameId);return e.Helpers.Timing.microSecondsToMilliseconds(i)}let s=a-i.minimumRecordTime();const{navigationId:o}=t.args.data;if(o){const e=i.navStartTimes().get(o);e&&(s=a-e.startTime)}return e.Types.Timing.MilliSeconds(s)}var St=Object.freeze({__proto__:null,TimelineUIUtils:ct,TimelineRecordStyle:ht,get NetworkCategory(){return mt},aggregatedStatsKey:ut,InvalidationsGroupElement:pt,previewElementSymbol:gt,EventDispatchTypeDescriptor:vt,TimelineCategory:Tt,TimelineDetailsContentHelper:ft,categoryBreakdownCacheSymbol:wt,timeStampForEventAdjustedForClosestNavigationIfPossible:yt});class bt extends a.ObjectWrapper.ObjectWrapper{mainTargetInternal;tracingModelInternal;filtersInternal;timelineModelInternal;frameModelInternal;windowInternal;willResolveNames=!1;recordStartTimeInternal;constructor(){super(),this.mainTargetInternal=null,this.tracingModelInternal=null,this.filtersInternal=[],this.timelineModelInternal=new r.TimelineModel.TimelineModelImpl,this.frameModelInternal=new r.TimelineFrameModel.TimelineFrameModel((e=>ct.eventStyle(e).category.name)),this.windowInternal={left:0,right:1/0},this.recordStartTimeInternal=void 0}setMainTarget(e){this.mainTargetInternal=e}mainTarget(){return this.mainTargetInternal}setRecordStartTime(e){this.recordStartTimeInternal=e}recordStartTime(){return this.recordStartTimeInternal}setFilters(e){this.filtersInternal=e}filters(){return this.filtersInternal}isVisible(e){return this.filtersInternal.every((t=>t.accept(e)))}async setTracingModel(e,t=!1){this.tracingModelInternal=e,this.timelineModelInternal.setEvents(e,t),await this.addSourceMapListeners();const i=this.timelineModelInternal.tracks().filter((e=>e.type===r.TimelineModel.TrackType.MainThread&&e.forMainFrame&&e.events.length)).map((e=>{const t=e.events[0];return{thread:t.thread,time:t.startTime}}));this.frameModelInternal.addTraceEvents(this.mainTargetInternal,this.timelineModelInternal.inspectedTargetEvents(),i),this.autoWindowTimes()}#u(){return this.timelineModel().cpuProfiles().flatMap((e=>e.nodes()||[]))}async addSourceMapListeners(){const e=new Set;for(const t of this.#u()){if(!t)continue;const i=this.#p(t);i&&e.add(i)}for(const t of e)t.sourceMapManager().addEventListener(n.SourceMapManager.Events.SourceMapAttached,this.#g,this);await this.#v()}#p(e){const t=e.target()?.model(n.DebuggerModel.DebuggerModel);if(!t)return null;const i=t.scriptForId(String(e.callFrame.scriptId));return!i||i.sourceMapURL?t:null}async#v(){for(const e of this.#u()){const t=await h.NamesResolver.resolveProfileFrameFunctionName(e.callFrame,e.target());e.setFunctionName(t)}}async#g(){this.willResolveNames||(this.willResolveNames=!0,setTimeout(this.resolveNamesAndUpdate.bind(this),500))}async resolveNamesAndUpdate(){this.willResolveNames=!1,await this.#v(),this.dispatchEventToListeners(Ct.NamesResolved)}tracingModel(){if(!this.tracingModelInternal)throw"call setTracingModel before accessing PerformanceModel";return this.tracingModelInternal}timelineModel(){return this.timelineModelInternal}frames(){return this.frameModelInternal.getFrames()}frameModel(){return this.frameModelInternal}setWindow(e,t){this.windowInternal=e,this.dispatchEventToListeners(Ct.WindowChanged,{window:e,animate:t})}window(){return this.windowInternal}autoWindowTimes(){const e=this.timelineModelInternal;let t=[];for(const i of e.tracks())i.type===r.TimelineModel.TrackType.MainThread&&i.forMainFrame&&(t=i.tasks);if(!t.length)return void this.setWindow({left:e.minimumRecordTime(),right:e.maximumRecordTime()});function i(e,i){let n=e,r=(t[n].startTime+t[n].endTime)/2,a=0;const s=Math.sign(i-e);for(let o=e;o!==i;o+=s){const e=t[o],i=(e.startTime+e.endTime)/2;a<.1*Math.abs(r-i)&&(n=o,r=i,a=0),a+=e.duration}return n}const n=i(t.length-1,0),a=i(0,n);let s=t[a].startTime,o=t[n].endTime;const l=o-s;l<.1*(e.maximumRecordTime()-e.minimumRecordTime())?(s=e.minimumRecordTime(),o=e.maximumRecordTime()):(s=Math.max(s-.05*l,e.minimumRecordTime()),o=Math.min(o+.05*l,e.maximumRecordTime())),this.setWindow({left:s,right:o})}}var Ct;!function(e){e.WindowChanged="WindowChanged",e.NamesResolved="NamesResolved"}(Ct||(Ct={}));var kt=Object.freeze({__proto__:null,PerformanceModel:bt,get Events(){return Ct}});const Pt={jsHeap:"JS Heap",documents:"Documents",nodes:"Nodes",listeners:"Listeners",gpuMemory:"GPU Memory",ss:"[{PH1} – {PH2}]"},Mt=i.i18n.registerUIStrings("panels/timeline/CountersGraph.ts",Pt),Et=i.i18n.getLocalizedString.bind(void 0,Mt);class xt extends c.Widget.VBox{delegate;calculator;model;header;toolbar;graphsContainer;canvasContainer;canvas;timelineGrid;counters;counterUI;countersByName;gpuMemoryCounter;#T=null;currentValuesBar;markerXPosition;constructor(e){super(),this.element.id="memory-graphs-container",this.delegate=e,this.calculator=new Rt,this.header=new c.Widget.HBox,this.header.element.classList.add("timeline-memory-header"),this.header.show(this.element),this.toolbar=new c.Toolbar.Toolbar("timeline-memory-toolbar"),this.header.element.appendChild(this.toolbar.element),this.graphsContainer=new c.Widget.VBox,this.graphsContainer.show(this.element);const t=new c.Widget.VBoxWithResizeCallback(this.resize.bind(this));t.show(this.graphsContainer.element),this.createCurrentValuesBar(),this.canvasContainer=t.element,this.canvasContainer.id="memory-graphs-canvas-container",this.canvas=document.createElement("canvas"),this.canvasContainer.appendChild(this.canvas),this.canvas.id="memory-counters-graph",this.canvasContainer.addEventListener("mouseover",this.onMouseMove.bind(this),!0),this.canvasContainer.addEventListener("mousemove",this.onMouseMove.bind(this),!0),this.canvasContainer.addEventListener("mouseleave",this.onMouseLeave.bind(this),!0),this.canvasContainer.addEventListener("click",this.onClick.bind(this),!0),this.timelineGrid=new d.TimelineGrid.TimelineGrid,this.canvasContainer.appendChild(this.timelineGrid.dividersElement),this.counters=[],this.counterUI=[],this.countersByName=new Map,this.countersByName.set("jsHeapSizeUsed",this.createCounter(Et(Pt.jsHeap),"hsl(220, 90%, 43%)",s.NumberUtilities.bytesToString)),this.countersByName.set("documents",this.createCounter(Et(Pt.documents),"hsl(0, 90%, 43%)")),this.countersByName.set("nodes",this.createCounter(Et(Pt.nodes),"hsl(120, 90%, 43%)")),this.countersByName.set("jsEventListeners",this.createCounter(Et(Pt.listeners),"hsl(38, 90%, 43%)")),this.gpuMemoryCounter=this.createCounter(Et(Pt.gpuMemory),"hsl(300, 90%, 43%)",s.NumberUtilities.bytesToString),this.countersByName.set("gpuMemoryUsedKB",this.gpuMemoryCounter)}setModel(e,t){if(this.#T=t,t){this.model!==e&&(this.model&&this.model.removeEventListener(Ct.WindowChanged,this.onWindowChanged,this),this.model=e,this.model&&this.model.addEventListener(Ct.WindowChanged,this.onWindowChanged,this)),this.calculator.setZeroTime(e?e.timelineModel().minimumRecordTime():0);for(let e=0;e<this.counters.length;++e)this.counters[e].reset(),this.counterUI[e].reset();this.scheduleRefresh();for(let e=0;e<t.length;++e){const i=t[e];if(i.name!==r.TimelineModel.RecordType.UpdateCounters)continue;const a=i.args.data;if(!a)return;for(const e in a){const t=this.countersByName.get(e);if(t){const{startTime:r}=n.TracingModel.timesForEventInMilliseconds(i);t.appendSample(r,a[e])}}const s="gpuMemoryLimitKB";s in a&&this.gpuMemoryCounter.setLimit(a[s])}}}createCurrentValuesBar(){this.currentValuesBar=this.graphsContainer.element.createChild("div"),this.currentValuesBar.id="counter-values-bar"}createCounter(e,t,i){const n=new It;return this.counters.push(n),this.counterUI.push(new Lt(this,e,t,n,i)),n}resizerElement(){return this.header.element}resize(){const e=this.canvas.parentElement;this.canvas.width=e.clientWidth*window.devicePixelRatio,this.canvas.height=e.clientHeight*window.devicePixelRatio,this.calculator.setDisplayWidth(this.canvas.width),this.refresh()}onWindowChanged(e){const t=e.data.window;this.calculator.setWindow(t.left,t.right),this.scheduleRefresh()}scheduleRefresh(){c.UIUtils.invokeOnceAfterBatchUpdate(this,this.refresh)}draw(){this.clear();for(const e of this.counters)e.calculateVisibleIndexes(this.calculator),e.calculateXValues(this.canvas.width);for(const e of this.counterUI)e.drawGraph(this.canvas)}onClick(e){const t=e.x-this.canvasContainer.getBoundingClientRect().left;let i,n=1/0;for(const e of this.counterUI){if(!e.counter.times.length)continue;const r=e.recordIndexAt(t),a=Math.abs(t*window.devicePixelRatio-e.counter.x[r]);a<n&&(n=a,i=e.counter.times[r])}void 0!==i&&this.#T&&this.delegate.selectEntryAtTime(this.#T,i)}onMouseLeave(e){delete this.markerXPosition,this.clearCurrentValueAndMarker()}clearCurrentValueAndMarker(){for(let e=0;e<this.counterUI.length;e++)this.counterUI[e].clearCurrentValueAndMarker()}onMouseMove(e){const t=e.x-this.canvasContainer.getBoundingClientRect().left;this.markerXPosition=t,this.refreshCurrentValues()}refreshCurrentValues(){if(void 0!==this.markerXPosition)for(let e=0;e<this.counterUI.length;++e)this.counterUI[e].updateCurrentValue(this.markerXPosition)}refresh(){this.timelineGrid.updateDividers(this.calculator),this.draw(),this.refreshCurrentValues()}clear(){const e=this.canvas.getContext("2d");if(!e)throw new Error("Unable to get canvas context");e.clearRect(0,0,e.canvas.width,e.canvas.height)}}class It{times;values;x;minimumIndex;maximumIndex;maxTime;minTime;limitValue;constructor(){this.times=[],this.values=[],this.x=[],this.minimumIndex=0,this.maximumIndex=0,this.maxTime=0,this.minTime=0}appendSample(e,t){this.values.length&&this.values[this.values.length-1]===t||(this.times.push(e),this.values.push(t))}reset(){this.times=[],this.values=[]}setLimit(e){this.limitValue=e}calculateBounds(){let e,t;for(let i=this.minimumIndex;i<=this.maximumIndex;i++){const n=this.values[i];(void 0===t||n<t)&&(t=n),(void 0===e||n>e)&&(e=n)}return t=t||0,e=e||1,this.limitValue&&(e>.5*this.limitValue&&(e=Math.max(e,this.limitValue)),t=Math.min(t,this.limitValue)),{min:t,max:e}}calculateVisibleIndexes(e){const t=e.minimumBoundary(),i=e.maximumBoundary();this.minimumIndex=s.NumberUtilities.clamp(s.ArrayUtilities.upperBound(this.times,t,s.ArrayUtilities.DEFAULT_COMPARATOR)-1,0,this.times.length-1),this.maximumIndex=s.NumberUtilities.clamp(s.ArrayUtilities.lowerBound(this.times,i,s.ArrayUtilities.DEFAULT_COMPARATOR),0,this.times.length-1),this.minTime=t,this.maxTime=i}calculateXValues(e){if(!this.values.length)return;const t=e/(this.maxTime-this.minTime);this.x=new Array(this.values.length);for(let e=this.minimumIndex+1;e<=this.maximumIndex;e++)this.x[e]=t*(this.times[e]-this.minTime)}}class Lt{countersPane;counter;formatter;setting;filter;range;value;graphColor;limitColor;graphYValues;verticalPadding;currentValueLabel;marker;constructor(e,t,i,n,r){this.countersPane=e,this.counter=n,this.formatter=r||s.NumberUtilities.withThousandsSeparator,this.setting=a.Settings.Settings.instance().createSetting("timelineCountersGraph-"+t,!0),this.setting.setTitle(t),this.filter=new c.Toolbar.ToolbarSettingCheckbox(this.setting,t),this.filter.inputElement.classList.add("-theme-preserve-input");const o=a.Color.parse(i);if(o){const e=o.setAlpha(.5).asString("rgba"),t=this.filter.element;e&&(t.style.backgroundColor=e),t.style.borderColor="transparent"}this.filter.inputElement.addEventListener("click",this.toggleCounterGraph.bind(this)),e.toolbar.appendToolbarItem(this.filter),this.range=this.filter.element.createChild("span","range"),this.value=e.currentValuesBar.createChild("span","memory-counter-value"),this.value.style.color=i,this.graphColor=i,o&&(this.limitColor=o.setAlpha(.3).asString("rgba")),this.graphYValues=[],this.verticalPadding=10,this.currentValueLabel=t,this.marker=e.canvasContainer.createChild("div","memory-counter-marker"),this.marker.style.backgroundColor=i,this.clearCurrentValueAndMarker()}reset(){this.range.textContent=""}setRange(e,t){const i=this.formatter(e),n=this.formatter(t);this.range.textContent=Et(Pt.ss,{PH1:i,PH2:n})}toggleCounterGraph(){this.value.classList.toggle("hidden",!this.filter.checked()),this.countersPane.refresh()}recordIndexAt(e){return s.ArrayUtilities.upperBound(this.counter.x,e*window.devicePixelRatio,s.ArrayUtilities.DEFAULT_COMPARATOR,this.counter.minimumIndex+1,this.counter.maximumIndex+1)-1}updateCurrentValue(e){if(!this.visible()||!this.counter.values.length||!this.counter.x)return;const t=this.recordIndexAt(e),i=s.NumberUtilities.withThousandsSeparator(this.counter.values[t]);this.value.textContent=`${this.currentValueLabel}: ${i}`;const n=this.graphYValues[t]/window.devicePixelRatio;this.marker.style.left=e+"px",this.marker.style.top=n+"px",this.marker.classList.remove("hidden")}clearCurrentValueAndMarker(){this.value.textContent="",this.marker.classList.add("hidden")}drawGraph(e){const t=e.getContext("2d");if(!t)throw new Error("Unable to get canvas context");const i=e.width,n=e.height-2*this.verticalPadding;if(n<=0)return void(this.graphYValues=[]);const r=this.verticalPadding,a=this.counter,s=a.values;if(!s.length)return;const o=a.calculateBounds(),l=o.min,d=o.max;if(this.setRange(l,d),!this.visible())return;const c=this.graphYValues,h=d-l,m=h?n/h:1;t.save(),t.lineWidth=window.devicePixelRatio,t.lineWidth%2&&t.translate(.5,.5),t.beginPath();let u=s[a.minimumIndex],p=Math.round(r+n-(u-l)*m);t.moveTo(0,p);let g=a.minimumIndex;for(;g<=a.maximumIndex;g++){const e=Math.round(a.x[g]);t.lineTo(e,p);const i=s[g];void 0!==i&&(u=i),p=Math.round(r+n-(u-l)*m),t.lineTo(e,p),c[g]=p}if(c.length=g,t.lineTo(i,p),t.strokeStyle=this.graphColor,t.stroke(),a.limitValue){const e=Math.round(r+n-(a.limitValue-l)*m);t.moveTo(0,e),t.lineTo(i,e),this.limitColor&&(t.strokeStyle=this.limitColor),t.stroke()}t.closePath(),t.restore()}visible(){return this.filter.checked()}}class Rt{minimumBoundaryInternal;maximumBoundaryInternal;workingArea;zeroTimeInternal;constructor(){this.minimumBoundaryInternal=0,this.maximumBoundaryInternal=0,this.workingArea=0,this.zeroTimeInternal=0}setZeroTime(e){this.zeroTimeInternal=e}computePosition(e){return(e-this.minimumBoundaryInternal)/this.boundarySpan()*this.workingArea}setWindow(e,t){this.minimumBoundaryInternal=e,this.maximumBoundaryInternal=t}setDisplayWidth(e){this.workingArea=e}formatValue(e,t){return i.TimeUtilities.preciseMillisToString(e-this.zeroTime(),t)}maximumBoundary(){return this.maximumBoundaryInternal}minimumBoundary(){return this.minimumBoundaryInternal}zeroTime(){return this.zeroTimeInternal}boundarySpan(){return this.maximumBoundaryInternal-this.minimumBoundaryInternal}}var Ft=Object.freeze({__proto__:null,CountersGraph:xt,Counter:It,CounterUI:Lt,Calculator:Rt});class Dt extends r.TimelineModelFilter.TimelineModelFilter{minimumRecordDuration;constructor(){super(),this.minimumRecordDuration=0}setMinimumRecordDuration(e){this.minimumRecordDuration=e}accept(e){return(e.endTime?e.endTime-e.startTime:0)>=this.minimumRecordDuration}}class Ut extends r.TimelineModelFilter.TimelineModelFilter{constructor(){super()}accept(e){return!ct.eventStyle(e).category.hidden}}class Ht extends r.TimelineModelFilter.TimelineModelFilter{regExpInternal;constructor(e){super(),this.setRegExp(e||null)}setRegExp(e){this.regExpInternal=e}regExp(){return this.regExpInternal}accept(e){return!this.regExpInternal||ct.testContentMatching(e,this.regExpInternal)}}var Nt=Object.freeze({__proto__:null,IsLong:Dt,Category:Ut,TimelineRegExp:Ht});const At={performance:"Performance",filter:"Filter",selfTime:"Self Time",totalTime:"Total Time",activity:"Activity",selectItemForDetails:"Select item for details.",notOptimizedS:"Not optimized: {PH1}",fms:"{PH1} ms",percentPlaceholder:"{PH1} %",chromeExtensionsOverhead:"[`Chrome` extensions overhead]",vRuntime:"[`V8` Runtime]",unattributed:"[unattributed]",javascript:"JavaScript",page:"Page",noGrouping:"No Grouping",groupByActivity:"Group by Activity",groupByCategory:"Group by Category",groupByDomain:"Group by Domain",groupByFrame:"Group by Frame",groupBySubdomain:"Group by Subdomain",groupByUrl:"Group by URL",groupBy:"Group by",filterCallTree:"Filter call tree",filterBottomup:"Filter bottom-up",heaviestStack:"Heaviest stack",showHeaviestStack:"Show Heaviest stack",hideHeaviestStack:"Hide Heaviest stack",heaviestStackShown:"Heaviest stack sidebar shown",heaviestStackHidden:"Heaviest stack sidebar hidden",timelineStack:"Timeline Stack"},Bt=i.i18n.registerUIStrings("panels/timeline/TimelineTreeView.ts",At),Wt=i.i18n.getLocalizedString.bind(void 0,Bt);class Vt extends c.Widget.VBox{modelInternal;#f;searchResults;linkifier;dataGrid;lastHoveredProfileNode;textFilterInternal;taskFilter;startTime;endTime;splitWidget;detailsView;searchableView;currentThreadSetting;lastSelectedNodeInternal;root;currentResult;textFilterUI;#w=null;constructor(){super(),this.modelInternal=null,this.#f=null,this.element.classList.add("timeline-tree-view"),this.searchResults=[]}static eventNameForSorting(e){if(r.TimelineModel.TimelineModelImpl.isJsFrameEvent(e)){const t=e.args.data;return t.functionName+"@"+(t.scriptId||t.url||"")}return e.name+":@"+r.TimelineProfileTree.eventURL(e)}setSearchableView(e){this.searchableView=e}setModelWithEvents(e,t,i=null){this.modelInternal=e,this.#w=i,this.#f=t,this.refreshTree()}setModel(e,t){this.setModelWithEvents(e,t?.eventsForTreeView()||null)}getToolbarInputAccessiblePlaceHolder(){return""}model(){return this.modelInternal}traceParseData(){return this.#w}init(){this.linkifier=new m.Linkifier.Linkifier,this.taskFilter=new r.TimelineModelFilter.ExclusiveNameFilter([r.TimelineModel.RecordType.Task]),this.textFilterInternal=new Ht,this.currentThreadSetting=a.Settings.Settings.instance().createSetting("timelineTreeCurrentThread",0),this.currentThreadSetting.addChangeListener(this.refreshTree,this);const e=[];this.populateColumns(e),this.splitWidget=new c.SplitWidget.SplitWidget(!0,!0,"timelineTreeViewDetailsSplitWidget");const t=new c.Widget.VBox,i=new c.Toolbar.Toolbar("",t.element);i.makeWrappable(!0),this.populateToolbar(i),this.dataGrid=new T.SortableDataGrid.SortableDataGrid({displayName:Wt(At.performance),columns:e,refreshCallback:void 0,editCallback:void 0,deleteCallback:void 0}),this.dataGrid.addEventListener(T.DataGrid.Events.SortingChanged,this.sortingChanged,this),this.dataGrid.element.addEventListener("mousemove",this.onMouseMove.bind(this),!0),this.dataGrid.setResizeMethod(T.DataGrid.ResizeMethod.Last),this.dataGrid.setRowContextMenuCallback(this.onContextMenu.bind(this)),this.dataGrid.asWidget().show(t.element),this.dataGrid.addEventListener(T.DataGrid.Events.SelectedNode,this.updateDetailsForSelection,this),this.detailsView=new c.Widget.VBox,this.detailsView.element.classList.add("timeline-details-view","timeline-details-view-body"),this.splitWidget.setMainWidget(t),this.splitWidget.setSidebarWidget(this.detailsView),this.splitWidget.hideSidebar(),this.splitWidget.show(this.element),this.splitWidget.addEventListener(c.SplitWidget.Events.ShowModeChanged,this.onShowModeChanged,this),this.lastSelectedNodeInternal}lastSelectedNode(){return this.lastSelectedNodeInternal}updateContents(e){this.setRange(e.startTime,e.endTime)}setRange(e,t){this.startTime=e,this.endTime=t,this.refreshTree()}filters(){return[this.taskFilter,this.textFilterInternal,...this.modelInternal?this.modelInternal.filters():[]]}filtersWithoutTextFilter(){return[this.taskFilter,...this.modelInternal?this.modelInternal.filters():[]]}textFilter(){return this.textFilterInternal}exposePercentages(){return!1}populateToolbar(e){const t=new c.Toolbar.ToolbarInput(Wt(At.filter),this.getToolbarInputAccessiblePlaceHolder());t.addEventListener(c.Toolbar.ToolbarInput.Event.TextChanged,(()=>{const e=t.value();this.textFilterInternal.setRegExp(e?s.StringUtilities.createPlainTextSearchRegex(e,"i"):null),this.refreshTree()}),this),this.textFilterUI=t,e.appendToolbarItem(t)}modelEvents(){return this.#f||[]}onHover(e){}appendContextMenuItems(e,t){}selectProfileNode(e,t){const i=[];let n=e;for(;n;n=n.parent)i.push(n);for(let e=i.length-1;e>0;--e){const t=this.dataGridNodeForTreeNode(i[e]);t&&t.dataGrid&&t.expand()}const r=this.dataGridNodeForTreeNode(e);r&&r.dataGrid&&(r.reveal(),r.select(t))}refreshTree(){if(this.linkifier.reset(),this.dataGrid.rootNode().removeChildren(),!this.modelInternal)return void this.updateDetailsForSelection();this.root=this.buildTree();const e=this.root.children();let t=0,i=0;const n=this.root.totalTime-this.root.selfTime;for(const n of e.values())t=Math.max(t,n.selfTime),i=Math.max(i,n.totalTime);for(const r of e.values()){const e=new zt(r,n,t,i,this);this.dataGrid.insertChild(e)}this.sortingChanged(),this.updateDetailsForSelection(),this.searchableView&&this.searchableView.refreshSearch();const r=this.dataGrid.rootNode();r.children.length>0&&r.children[0].select(!0)}buildTree(){throw new Error("Not Implemented")}buildTopDownTree(e,t){return new r.TimelineProfileTree.TopDownRootNode(this.modelEvents(),this.filters(),this.startTime,this.endTime,e,t)}populateColumns(e){e.push({id:"self",title:Wt(At.selfTime),width:"120px",fixedWidth:!0,sortable:!0}),e.push({id:"total",title:Wt(At.totalTime),width:"120px",fixedWidth:!0,sortable:!0}),e.push({id:"activity",title:Wt(At.activity),disclosure:!0,sortable:!0})}sortingChanged(){const e=this.dataGrid.sortColumnId();if(!e)return;let t;switch(e){case"startTime":t=function(e,t){const i=t,n=e.profileNode.event,r=i.profileNode.event;return n.startTime-r.startTime};break;case"self":t=i.bind(null,"selfTime");break;case"total":t=i.bind(null,"totalTime");break;case"activity":t=function(e,t){const i=t,n=e.profileNode.event,r=i.profileNode.event,a=Vt.eventNameForSorting(n),s=Vt.eventNameForSorting(r);return a.localeCompare(s)};break;default:return void console.assert(!1,"Unknown sort field: "+e)}function i(e,t,i){const n=i;return t.profileNode[e]-n.profileNode[e]}this.dataGrid.sortNodes(t,!this.dataGrid.isSortOrderAscending())}onShowModeChanged(){this.splitWidget.showMode()!==c.SplitWidget.ShowMode.OnlyMain&&(this.lastSelectedNodeInternal=void 0,this.updateDetailsForSelection())}updateDetailsForSelection(){const e=this.dataGrid.selectedNode?this.dataGrid.selectedNode.profileNode:null;if(e===this.lastSelectedNodeInternal)return;if(this.lastSelectedNodeInternal=e,this.splitWidget.showMode()===c.SplitWidget.ShowMode.OnlyMain)return;if(this.detailsView.detachChildWidgets(),this.detailsView.element.removeChildren(),e&&this.showDetailsForNode(e))return;const t=this.detailsView.element.createChild("div","full-widget-dimmed-banner");c.UIUtils.createTextChild(t,Wt(At.selectItemForDetails))}showDetailsForNode(e){return!1}onMouseMove(e){const t=e.target&&e.target instanceof Node?this.dataGrid.dataGridNodeFromNode(e.target):null,i=t&&t._profileNode;i!==this.lastHoveredProfileNode&&(this.lastHoveredProfileNode=i,this.onHover(i))}onContextMenu(e,t){const i=t;i.linkElement&&!e.containsTarget(i.linkElement)&&e.appendApplicableItems(i.linkElement);const n=i.profileNode;n&&this.appendContextMenuItems(e,n)}dataGridNodeForTreeNode(e){return Gt.get(e)||null}onSearchCanceled(){this.searchResults=[],this.currentResult=0}performSearch(e,t,i){if(this.searchResults=[],this.currentResult=0,!this.root)return;const n=e.toSearchRegex();this.searchResults=this.root.searchTree((e=>ct.testContentMatching(e,n.regex))),this.searchableView.updateSearchMatchesCount(this.searchResults.length)}jumpToNextSearchResult(){this.searchResults.length&&void 0!==this.currentResult&&(this.selectProfileNode(this.searchResults[this.currentResult],!1),this.currentResult=s.NumberUtilities.mod(this.currentResult+1,this.searchResults.length))}jumpToPreviousSearchResult(){this.searchResults.length&&void 0!==this.currentResult&&(this.selectProfileNode(this.searchResults[this.currentResult],!1),this.currentResult=s.NumberUtilities.mod(this.currentResult-1,this.searchResults.length))}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!0}}class Ot extends T.SortableDataGrid.SortableDataGridNode{populated;profileNode;treeView;grandTotalTime;maxSelfTime;maxTotalTime;linkElement;constructor(e,t,i,n,r){super(null,!1),this.populated=!1,this.profileNode=e,this.treeView=r,this.grandTotalTime=t,this.maxSelfTime=i,this.maxTotalTime=n,this.linkElement=null}createCell(e){return"activity"===e?this.createNameCell(e):this.createValueCell(e)||super.createCell(e)}createNameCell(e){const t=this.createTD(e),i=t.createChild("div","name-container"),n=i.createChild("div","activity-icon-container"),r=n.createChild("div","activity-icon"),a=i.createChild("div","activity-name"),s=this.profileNode.event;if(this.profileNode.isGroupNode()){const e=this.treeView.displayInfoForGroupNode(this.profileNode);a.textContent=e.name,r.style.backgroundColor=e.color,e.icon&&n.insertBefore(e.icon,r)}else if(s){const e=s.args.data,t=e&&e.deoptReason;t&&(i.createChild("div","activity-warning").title=Wt(At.notOptimizedS,{PH1:t})),a.textContent=ct.eventTitle(s);const n=this.treeView.modelInternal?.timelineModel().targetByEvent(s)||null,o=this.treeView.linkifier,l=Boolean(this.treeView.modelInternal?.timelineModel().isFreshRecording());this.linkElement=ct.linkifyTopCallFrame(s,n,o,l),this.linkElement&&i.createChild("div","activity-link").appendChild(this.linkElement);const d=ct.eventStyle(s).category;c.ARIAUtils.setLabel(r,d.title),r.style.backgroundColor=d.color}return t}createValueCell(e){if("self"!==e&&"total"!==e&&"startTime"!==e)return null;let t,i,r,a=!1;switch(e){case"startTime":{r=this.profileNode.event;const e=this.treeView.model();if(!e)throw new Error("Unable to find model for tree view");t=((r&&n.TracingModel.timesForEventInMilliseconds(r))?.startTime??0)-e.timelineModel().minimumRecordTime()}break;case"self":t=this.profileNode.selfTime,i=this.maxSelfTime,a=!0;break;case"total":t=this.profileNode.totalTime,i=this.maxTotalTime,a=!0;break;default:return null}const s=this.createTD(e);s.className="numeric-column",s.setAttribute("title",Wt(At.fms,{PH1:t.toFixed(4)}));const o=s.createChild("div");return o.createChild("span").textContent=Wt(At.fms,{PH1:t.toFixed(1)}),a&&this.treeView.exposePercentages()&&(o.createChild("span","percent-column").textContent=Wt(At.percentPlaceholder,{PH1:(t/this.grandTotalTime*100).toFixed(1)})),i&&(o.classList.add("background-percent-bar"),s.createChild("div","background-bar-container").createChild("div","background-bar").style.width=(100*t/i).toFixed(1)+"%"),s}}class zt extends Ot{constructor(e,t,i,n,r){super(e,t,i,n,r),this.setHasChildren(this.profileNode.hasChildren()),Gt.set(e,this)}populate(){if(!this.populated&&(this.populated=!0,this.profileNode.children))for(const e of this.profileNode.children().values()){const t=new zt(e,this.grandTotalTime,this.maxSelfTime,this.maxTotalTime,this.treeView);this.insertChildOrdered(t)}}}const Gt=new WeakMap;class _t extends Vt{groupBySetting;stackView;executionContextNamesByOrigin=new Map;constructor(){super(),this.groupBySetting=a.Settings.Settings.instance().createSetting("timelineTreeGroupBy",_t.GroupBy.None),this.groupBySetting.addChangeListener(this.refreshTree.bind(this)),this.init(),this.stackView=new Jt(this),this.stackView.addEventListener(Jt.Events.SelectionChanged,this.onStackViewSelectionChanged,this)}setGroupBySettingForTests(e){this.groupBySetting.set(e)}setModelWithEvents(e,t,i=null){super.setModelWithEvents(e,t,i)}setModel(e,t){super.setModel(e,t)}updateContents(e){this.updateExtensionResolver(),super.updateContents(e);const t=this.dataGrid.rootNode();t.children.length&&t.children[0].select(!0)}updateExtensionResolver(){this.executionContextNamesByOrigin=new Map;for(const e of n.TargetManager.TargetManager.instance().models(n.RuntimeModel.RuntimeModel))for(const t of e.executionContexts())this.executionContextNamesByOrigin.set(t.origin,t.name)}beautifyDomainName(e){return _t.isExtensionInternalURL(e)?e=Wt(At.chromeExtensionsOverhead):_t.isV8NativeURL(e)?e=Wt(At.vRuntime):e.startsWith("chrome-extension")&&(e=this.executionContextNamesByOrigin.get(e)||e),e}displayInfoForGroupNode(e){const t=ct.categories(),i=e.id?ct.eventColor(e.event):t.other.color,n=Wt(At.unattributed),a="symbol"==typeof e.id?void 0:e.id;switch(this.groupBySetting.get()){case _t.GroupBy.Category:{const e=a?t[a]||t.other:{title:n,color:n};return{name:e.title,color:e.color,icon:void 0}}case _t.GroupBy.Domain:case _t.GroupBy.Subdomain:return{name:(a?this.beautifyDomainName(a):void 0)||n,color:i,icon:void 0};case _t.GroupBy.EventName:if(!e.event)throw new Error("Unable to find event for group by operation");return{name:r.TimelineModel.TimelineModelImpl.isJsFrameEvent(e.event)?Wt(At.javascript):ct.eventTitle(e.event),color:r.TimelineModel.TimelineModelImpl.isJsFrameEvent(e.event)?ct.eventStyle(e.event).category.color:i,icon:void 0};case _t.GroupBy.URL:break;case _t.GroupBy.Frame:{if(!this.modelInternal)throw new Error("Unable to find model for group by frame operation");const e=a?this.modelInternal.timelineModel().pageFrameById(a):void 0;return{name:e?ct.displayNameForFrame(e,80):Wt(At.page),color:i,icon:void 0}}default:console.assert(!1,"Unexpected grouping type")}return{name:a||n,color:i,icon:void 0}}populateToolbar(e){super.populateToolbar(e);const t=_t.GroupBy,i=[{label:Wt(At.noGrouping),value:t.None},{label:Wt(At.groupByActivity),value:t.EventName},{label:Wt(At.groupByCategory),value:t.Category},{label:Wt(At.groupByDomain),value:t.Domain},{label:Wt(At.groupByFrame),value:t.Frame},{label:Wt(At.groupBySubdomain),value:t.Subdomain},{label:Wt(At.groupByUrl),value:t.URL}];e.appendToolbarItem(new c.Toolbar.ToolbarSettingComboBox(i,this.groupBySetting,Wt(At.groupBy))),e.appendSpacer(),e.appendToolbarItem(this.splitWidget.createShowHideSidebarButton(Wt(At.showHeaviestStack),Wt(At.hideHeaviestStack),Wt(At.heaviestStackShown),Wt(At.heaviestStackHidden)))}buildHeaviestStack(e){console.assert(Boolean(e.parent),"Attempt to build stack for tree root");let t=[];for(let i=e;i&&i.parent;i=i.parent)t.push(i);t=t.reverse();for(let i=e;i&&i.children()&&i.children().size;){const e=Array.from(i.children().values());i=e.reduce(((e,t)=>e.totalTime>t.totalTime?e:t)),t.push(i)}return t}exposePercentages(){return!0}onStackViewSelectionChanged(){const e=this.stackView.selectedTreeNode();e&&this.selectProfileNode(e,!0)}showDetailsForNode(e){const t=this.buildHeaviestStack(e);return this.stackView.setStack(t,e),this.stackView.show(this.detailsView.element),!0}groupingFunction(e){const t=_t.GroupBy;switch(e){case t.None:return null;case t.EventName:return e=>ct.eventStyle(e).title;case t.Category:return e=>ct.eventStyle(e).category.name;case t.Subdomain:return this.domainByEvent.bind(this,!1);case t.Domain:return this.domainByEvent.bind(this,!0);case t.URL:return e=>r.TimelineProfileTree.eventURL(e)||"";case t.Frame:return e=>r.TimelineModel.EventOnTimelineData.forEvent(e).frameId||"";default:return console.assert(!1,`Unexpected aggregation setting: ${e}`),null}}domainByEvent(e,t){const i=r.TimelineProfileTree.eventURL(t);if(!i)return"";if(_t.isExtensionInternalURL(i))return _t.extensionInternalPrefix;if(_t.isV8NativeURL(i))return _t.v8NativePrefix;const n=a.ParsedURL.ParsedURL.fromString(i);if(!n)return"";if("chrome-extension"===n.scheme)return n.scheme+"://"+n.host;if(!e)return n.host;if(/^[.0-9]+$/.test(n.host))return n.host;const s=/([^.]*\.)?[^.]*$/.exec(n.host);return s&&s[0]||""}appendContextMenuItems(e,t){if(this.groupBySetting.get()!==_t.GroupBy.Frame)return;if(!t.isGroupNode())return;if(!this.modelInternal)return;const i=this.modelInternal.timelineModel().pageFrameById(t.id);i&&i.ownerNode&&e.appendApplicableItems(i.ownerNode)}static isExtensionInternalURL(e){return e.startsWith(_t.extensionInternalPrefix)}static isV8NativeURL(e){return e.startsWith(_t.v8NativePrefix)}static extensionInternalPrefix="extensions::";static v8NativePrefix="native "}!function(e){let t;!function(e){e.None="None",e.EventName="EventName",e.Category="Category",e.Domain="Domain",e.Subdomain="Subdomain",e.URL="URL",e.Frame="Frame"}(t=e.GroupBy||(e.GroupBy={}))}(_t||(_t={}));class jt extends _t{constructor(){super(),this.dataGrid.markColumnAsSortedBy("total",T.DataGrid.Order.Descending)}getToolbarInputAccessiblePlaceHolder(){return Wt(At.filterCallTree)}buildTree(){const e=this.groupBySetting.get();return this.buildTopDownTree(!1,this.groupingFunction(e))}}class qt extends _t{constructor(){super(),this.dataGrid.markColumnAsSortedBy("self",T.DataGrid.Order.Descending)}getToolbarInputAccessiblePlaceHolder(){return Wt(At.filterBottomup)}buildTree(){return new r.TimelineProfileTree.BottomUpRootNode(this.modelEvents(),this.textFilter(),this.filtersWithoutTextFilter(),this.startTime,this.endTime,this.groupingFunction(this.groupBySetting.get()))}}class Jt extends(a.ObjectWrapper.eventMixin(c.Widget.VBox)){treeView;dataGrid;constructor(e){super();this.element.createChild("div","timeline-stack-view-header").textContent=Wt(At.heaviestStack),this.treeView=e;const t=[{id:"total",title:Wt(At.totalTime),fixedWidth:!0,width:"110px"},{id:"activity",title:Wt(At.activity)}];this.dataGrid=new T.ViewportDataGrid.ViewportDataGrid({displayName:Wt(At.timelineStack),columns:t,deleteCallback:void 0,editCallback:void 0,refreshCallback:void 0}),this.dataGrid.setResizeMethod(T.DataGrid.ResizeMethod.Last),this.dataGrid.addEventListener(T.DataGrid.Events.SelectedNode,this.onSelectionChanged,this),this.dataGrid.asWidget().show(this.element)}setStack(e,t){const i=this.dataGrid.rootNode();i.removeChildren();let n=null;const r=Math.max.apply(Math,e.map((e=>e.totalTime)));for(const a of e){const e=new Ot(a,r,r,r,this.treeView);i.appendChild(e),a===t&&(n=e)}n&&n.revealAndSelect()}selectedTreeNode(){const e=this.dataGrid.selectedNode;return e&&e.profileNode}onSelectionChanged(){this.dispatchEventToListeners(Jt.Events.SelectionChanged)}}!function(e){let t;!function(e){e.SelectionChanged="SelectionChanged"}(t=e.Events||(e.Events={}))}(Jt||(Jt={}));var $t=Object.freeze({__proto__:null,TimelineTreeView:Vt,GridNode:Ot,TreeGridNode:zt,get AggregatedTimelineTreeView(){return _t},CallTreeTimelineTreeView:jt,BottomUpTimelineTreeView:qt,get TimelineStackView(){return Jt}});const Xt={filterEventLog:"Filter event log",startTime:"Start Time",durationFilter:"Duration filter",Dms:"{PH1} ms",all:"All"},Yt=i.i18n.registerUIStrings("panels/timeline/EventsTimelineTreeView.ts",Xt),Kt=i.i18n.getLocalizedString.bind(void 0,Yt);class Zt extends Vt{filtersControl;delegate;currentTree;constructor(e){super(),this.filtersControl=new Qt,this.filtersControl.addEventListener("FilterChanged",this.onFilterChanged,this),this.init(),this.delegate=e,this.dataGrid.markColumnAsSortedBy("startTime",T.DataGrid.Order.Ascending),this.splitWidget.showBoth()}filters(){return[...super.filters(),...this.filtersControl.filters()]}updateContents(e){super.updateContents(e),De.isTraceEventSelection(e.object)&&this.selectEvent(e.object,!0)}getToolbarInputAccessiblePlaceHolder(){return Kt(Xt.filterEventLog)}buildTree(){return this.currentTree=this.buildTopDownTree(!0,null),this.currentTree}onFilterChanged(){const e=this.lastSelectedNode(),t=e&&e.event;this.refreshTree(),t&&this.selectEvent(t,!1)}findNodeWithEvent(e){if("RunTask"===e.name)return null;const t=[this.currentTree.children().values()];for(;t.length;){const{done:i,value:n}=t[t.length-1].next();if(i)t.pop();else{if(n.event===e)return n;t.push(n.children().values())}}return null}selectEvent(e,t){const i=this.findNodeWithEvent(e);if(i&&(this.selectProfileNode(i,!1),t)){const e=this.dataGridNodeForTreeNode(i);e&&e.expand()}}populateColumns(e){e.push({id:"startTime",title:Kt(Xt.startTime),width:"80px",fixedWidth:!0,sortable:!0}),super.populateColumns(e),e.filter((e=>e.fixedWidth)).forEach((e=>{e.width="80px"}))}populateToolbar(e){super.populateToolbar(e),this.filtersControl.populateToolbar(e)}showDetailsForNode(e){const t=e.event;if(!t)return!1;const i=this.model();return!!i&&(ct.buildTraceEventDetails(t,i.timelineModel(),this.linkifier,!1,this.traceParseData()).then((e=>this.detailsView.element.appendChild(e))),!0)}onHover(e){this.delegate.highlightEvent(e&&e.event)}}class Qt extends a.ObjectWrapper.ObjectWrapper{categoryFilter;durationFilter;filtersInternal;constructor(){super(),this.categoryFilter=new Ut,this.durationFilter=new Dt,this.filtersInternal=[this.categoryFilter,this.durationFilter]}filters(){return this.filtersInternal}populateToolbar(e){const t=new c.Toolbar.ToolbarComboBox(function(){const e=t.selectedOption().value,i=parseInt(e,10);this.durationFilter.setMinimumRecordDuration(i),this.notifyFiltersChanged()}.bind(this),Kt(Xt.durationFilter));for(const e of Qt.durationFilterPresetsMs)t.addOption(t.createOption(e?`≥ ${Kt(Xt.Dms,{PH1:e})}`:Kt(Xt.all),String(e)));e.appendToolbarItem(t);const i=new Map,n=ct.categories();for(const t in n){const a=n[t];if(!a.visible)continue;const s=new c.Toolbar.ToolbarCheckbox(a.title,void 0,r.bind(this,t));s.setChecked(!0),s.inputElement.style.backgroundColor=a.color,i.set(a.name,s),e.appendToolbarItem(s)}function r(e){const t=ct.categories(),n=i.get(e);t[e].hidden=!n||!n.checked(),this.notifyFiltersChanged()}}notifyFiltersChanged(){this.dispatchEventToListeners("FilterChanged")}static durationFilterPresetsMs=[0,1,15]}var ei=Object.freeze({__proto__:null,EventsTimelineTreeView:Zt,Filters:Qt});class ti extends c.SplitWidget.SplitWidget{model;showPaintProfilerCallback;rightSplitWidget;layerViewHost;layers3DView;frameLayerTree;updateWhenVisible;constructor(e,t){super(!0,!1,"timelineLayersView"),this.model=e,this.showPaintProfilerCallback=t,this.element.classList.add("timeline-layers-view"),this.rightSplitWidget=new c.SplitWidget.SplitWidget(!0,!0,"timelineLayersViewDetails"),this.rightSplitWidget.element.classList.add("timeline-layers-view-properties"),this.setMainWidget(this.rightSplitWidget);const i=new c.Widget.VBox;this.setSidebarWidget(i),this.layerViewHost=new f.LayerViewHost.LayerViewHost;const n=new f.LayerTreeOutline.LayerTreeOutline(this.layerViewHost);i.element.appendChild(n.element),this.layers3DView=new f.Layers3DView.Layers3DView(this.layerViewHost),this.layers3DView.addEventListener(f.Layers3DView.Events.PaintProfilerRequested,this.onPaintProfilerRequested,this),this.rightSplitWidget.setMainWidget(this.layers3DView);const r=new f.LayerDetailsView.LayerDetailsView(this.layerViewHost);this.rightSplitWidget.setSidebarWidget(r),r.addEventListener(f.LayerDetailsView.Events.PaintProfilerRequested,this.onPaintProfilerRequested,this)}showLayerTree(e){this.frameLayerTree=e,this.isShowing()?this.update():this.updateWhenVisible=!0}wasShown(){this.updateWhenVisible&&(this.updateWhenVisible=!1,this.update())}async onPaintProfilerRequested(e){const t=e.data,i=await this.layers3DView.snapshotForSelection(t);i&&this.showPaintProfilerCallback(i.snapshot)}update(){this.frameLayerTree&&this.frameLayerTree.layerTreePromise().then((e=>this.layerViewHost.setLayerTree(e)))}}var ii=Object.freeze({__proto__:null,TimelineLayersView:ti});const ni=new CSSStyleSheet;ni.replaceSync(".paint-profiler-image-view{overflow:hidden}.paint-profiler-image-view .paint-profiler-image-container{transform-origin:0 0}.paint-profiler-image-view .paint-profiler-image-container div{border-color:var(--color-details-hairline);border-style:solid;z-index:100;position:absolute;top:0;left:0}.paint-profiler-image-view img{border:solid 1px var(--color-background-inverted)}\n/*# sourceURL=timelinePaintProfiler.css */\n");class ri extends c.SplitWidget.SplitWidget{frameModel;logAndImageSplitWidget;imageView;paintProfilerView;logTreeView;needsUpdateWhenVisible;pendingSnapshot;event;paintProfilerModel;lastLoadedSnapshot;constructor(e){super(!1,!1),this.element.classList.add("timeline-paint-profiler-view"),this.setSidebarSize(60),this.setResizable(!1),this.frameModel=e,this.logAndImageSplitWidget=new c.SplitWidget.SplitWidget(!0,!1),this.logAndImageSplitWidget.element.classList.add("timeline-paint-profiler-log-split"),this.setMainWidget(this.logAndImageSplitWidget),this.imageView=new ai,this.logAndImageSplitWidget.setMainWidget(this.imageView),this.paintProfilerView=new f.PaintProfilerView.PaintProfilerView(this.imageView.showImage.bind(this.imageView)),this.paintProfilerView.addEventListener(f.PaintProfilerView.Events.WindowChanged,this.onWindowChanged,this),this.setSidebarWidget(this.paintProfilerView),this.logTreeView=new f.PaintProfilerView.PaintProfilerCommandLogView,this.logAndImageSplitWidget.setSidebarWidget(this.logTreeView),this.needsUpdateWhenVisible=!1,this.pendingSnapshot=null,this.event=null,this.paintProfilerModel=null,this.lastLoadedSnapshot=null}wasShown(){super.wasShown(),this.needsUpdateWhenVisible&&(this.needsUpdateWhenVisible=!1,this.update())}setSnapshot(e){this.releaseSnapshot(),this.pendingSnapshot=e,this.event=null,this.updateWhenVisible()}setEvent(e,t){return this.releaseSnapshot(),this.paintProfilerModel=e,this.pendingSnapshot=null,this.event=t,this.updateWhenVisible(),this.event.name===r.TimelineModel.RecordType.Paint?Boolean(r.TimelineModel.EventOnTimelineData.forEvent(t).picture):this.event.name===r.TimelineModel.RecordType.RasterTask&&this.frameModel.hasRasterTile(this.event)}updateWhenVisible(){this.isShowing()?this.update():this.needsUpdateWhenVisible=!0}update(){let e;if(this.logTreeView.setCommandLog([]),this.paintProfilerView.setSnapshotAndLog(null,[],null),this.pendingSnapshot)e=Promise.resolve({rect:null,snapshot:this.pendingSnapshot});else if(this.event&&this.event.name===r.TimelineModel.RecordType.Paint&&this.paintProfilerModel){const t=r.TimelineModel.EventOnTimelineData.forEvent(this.event).picture.getSnapshot();e=this.paintProfilerModel.loadSnapshot(t.skp64).then((e=>e&&{rect:null,snapshot:e}))}else{if(!this.event||this.event.name!==r.TimelineModel.RecordType.RasterTask)return void console.assert(!1,"Unexpected event type or no snapshot");e=this.frameModel.rasterTilePromise(this.event)}function t(e,t,i){this.logTreeView.setCommandLog(i||[]),this.paintProfilerView.setSnapshotAndLog(e,i||[],t)}e.then((e=>{if(this.releaseSnapshot(),!e)return void this.imageView.showImage();const i=e.snapshot;this.lastLoadedSnapshot=i,this.imageView.setMask(e.rect),i.commandLog().then((n=>t.call(this,i,e.rect,n||[])))}))}releaseSnapshot(){this.lastLoadedSnapshot&&(this.lastLoadedSnapshot.release(),this.lastLoadedSnapshot=null)}onWindowChanged(){this.logTreeView.updateWindow(this.paintProfilerView.selectionWindow())}}class ai extends c.Widget.Widget{imageContainer;imageElement;maskElement;transformController;maskRectangle;constructor(){super(!0),this.contentElement.classList.add("fill","paint-profiler-image-view"),this.imageContainer=this.contentElement.createChild("div","paint-profiler-image-container"),this.imageElement=this.imageContainer.createChild("img"),this.maskElement=this.imageContainer.createChild("div"),this.imageElement.addEventListener("load",this.updateImagePosition.bind(this),!1),this.transformController=new f.TransformController.TransformController(this.contentElement,!0),this.transformController.addEventListener(f.TransformController.Events.TransformChanged,this.updateImagePosition,this)}onResize(){this.imageElement.src&&this.updateImagePosition()}updateImagePosition(){const e=this.imageElement.naturalWidth,t=this.imageElement.naturalHeight,i=this.contentElement.clientWidth,n=this.contentElement.clientHeight,r=.1*i,a=.1*n,s=(i-r)/e,o=(n-a)/t,l=Math.min(s,o);if(this.maskRectangle){const i=this.maskElement.style;i.width=e+"px",i.height=t+"px",i.borderLeftWidth=this.maskRectangle.x+"px",i.borderTopWidth=this.maskRectangle.y+"px",i.borderRightWidth=e-this.maskRectangle.x-this.maskRectangle.width+"px",i.borderBottomWidth=t-this.maskRectangle.y-this.maskRectangle.height+"px"}this.transformController.setScaleConstraints(.5,10/l);let d=(new WebKitCSSMatrix).scale(this.transformController.scale(),this.transformController.scale()).translate(i/2,n/2).scale(l,l).translate(-e/2,-t/2);const h=c.Geometry.boundsForTransformedPoints(d,[0,0,0,e,t,0]);this.transformController.clampOffsets(r-h.maxX,i-r-h.minX,a-h.maxY,n-a-h.minY),d=(new WebKitCSSMatrix).translate(this.transformController.offsetX(),this.transformController.offsetY()).multiply(d),this.imageContainer.style.webkitTransform=d.toString()}showImage(e){this.imageContainer.classList.toggle("hidden",!e),e&&(this.imageElement.src=e)}setMask(e){this.maskRectangle=e,this.maskElement.classList.toggle("hidden",!e)}wasShown(){super.wasShown(),this.registerCSSFiles([ni])}}var si=Object.freeze({__proto__:null,TimelinePaintProfilerView:ri,TimelinePaintImageView:ai});const oi={summary:"Summary",bottomup:"Bottom-Up",callTree:"Call Tree",eventLog:"Event Log",estimated:"estimated",totalBlockingTimeSmss:"Total blocking time: {PH1}ms{PH2}",learnMore:"Learn more",layers:"Layers",paintProfiler:"Paint Profiler",rangeSS:"Range:  {PH1} – {PH2}"},li=i.i18n.registerUIStrings("panels/timeline/TimelineDetailsView.ts",oi),di=i.i18n.getLocalizedString.bind(void 0,li);class ci extends c.Widget.VBox{detailsLinkifier;tabbedPane;defaultDetailsWidget;defaultDetailsContentElement;rangeDetailViews;additionalMetricsToolbar;model;#f;lazyPaintProfilerView;lazyLayersView;preferredTabId;selection;#y=null;#e=null;constructor(e){super(),this.element.classList.add("timeline-details"),this.detailsLinkifier=new m.Linkifier.Linkifier,this.tabbedPane=new c.TabbedPane.TabbedPane,this.tabbedPane.show(this.element),this.defaultDetailsWidget=new c.Widget.VBox,this.defaultDetailsWidget.element.classList.add("timeline-details-view"),this.defaultDetailsContentElement=this.defaultDetailsWidget.element.createChild("div","timeline-details-view-body vbox"),this.appendTab(hi.Details,di(oi.summary),this.defaultDetailsWidget),this.setPreferredTab(hi.Details),this.rangeDetailViews=new Map;const t=new qt;this.appendTab(hi.BottomUp,di(oi.bottomup),t),this.rangeDetailViews.set(hi.BottomUp,t);const i=new jt;this.appendTab(hi.CallTree,di(oi.callTree),i),this.rangeDetailViews.set(hi.CallTree,i);const n=new Zt(e);this.appendTab(hi.EventLog,di(oi.eventLog),n),this.rangeDetailViews.set(hi.EventLog,n),this.additionalMetricsToolbar=new c.Toolbar.Toolbar("timeline-additional-metrics"),this.element.appendChild(this.additionalMetricsToolbar.element),this.tabbedPane.addEventListener(c.TabbedPane.Events.TabSelected,this.tabSelected,this)}setModel(e,t,i,n){this.model!==e&&(this.model&&this.model.removeEventListener(Ct.WindowChanged,this.onWindowChanged,this),this.model=e,this.model&&this.model.addEventListener(Ct.WindowChanged,this.onWindowChanged,this)),this.#y=t,this.#f=n,this.#e=i,this.tabbedPane.closeTabs([hi.PaintProfiler,hi.LayerViewer],!1);for(const i of this.rangeDetailViews.values())i.setModelWithEvents(e,n,t);if(this.lazyPaintProfilerView=null,this.lazyLayersView=null,this.setSelection(null),this.additionalMetricsToolbar.removeToolbarItems(),e&&e.timelineModel()){const{estimated:t,time:i}=e.timelineModel().totalBlockingTime(),n=t?` (${di(oi.estimated)})`:"",r=di(oi.totalBlockingTimeSmss,{PH1:i.toFixed(2),PH2:n}),a=document.createElement("span"),s=c.XLink.XLink.create("https://web.dev/tbt/",di(oi.learnMore));s.style.margin="3px",a.appendChild(s),this.additionalMetricsToolbar.appendText(r),this.additionalMetricsToolbar.appendToolbarItem(new c.Toolbar.ToolbarItem(a))}}setContent(e){const t=this.tabbedPane.otherTabs(hi.Details);for(let e=0;e<t.length;++e)this.rangeDetailViews.has(t[e])||this.tabbedPane.closeTab(t[e]);this.defaultDetailsContentElement.removeChildren(),this.defaultDetailsContentElement.appendChild(e)}updateContents(){const e=this.rangeDetailViews.get(this.tabbedPane.selectedTabId||"");if(e){const t=this.model.window();e.updateContents(this.selection||De.fromRange(t.left,t.right))}}appendTab(e,t,i,n){this.tabbedPane.appendTab(e,t,i,void 0,void 0,n),this.preferredTabId!==this.tabbedPane.selectedTabId&&this.tabbedPane.selectTab(e)}headerElement(){return this.tabbedPane.headerElement()}setPreferredTab(e){this.preferredTabId=e}onWindowChanged(){this.selection||this.updateContentsFromWindow()}updateContentsFromWindow(){if(!this.model)return void this.setContent(c.Fragment.html`<div>`);const e=this.model.window();this.updateSelectedRangeStats(e.left,e.right),this.updateContents()}#S(e){if(!this.#e)return null;const t=e.idle?e.startTime:e.endTime,i=this.#e.frameByTimestamp(t);return i&&i.timestamp-e.endTime<10?i:null}setSelection(e){if(this.detailsLinkifier.reset(),this.selection=e,!this.selection)return void this.updateContentsFromWindow();const t=this.selection.object;if(De.isTraceEventSelection(t)){const e=t;ct.buildTraceEventDetails(e,this.model.timelineModel(),this.detailsLinkifier,!0,this.#y).then((t=>this.appendDetailsTabsForTraceEventAndShowDetails(e,t)))}else if(De.isFrameObject(t)){const e=t,i=this.#S(e);if(this.setContent(ct.generateDetailsContentForFrame(e,i)),e.layerTree){const t=this.layersView();t.showLayerTree(e.layerTree),this.tabbedPane.hasTab(hi.LayerViewer)||this.appendTab(hi.LayerViewer,di(oi.layers),t)}}else if(De.isNetworkRequestSelection(t)){const e=t;ct.buildNetworkRequestDetails(e,this.model.timelineModel(),this.detailsLinkifier).then(this.setContent.bind(this))}else De.isRangeSelection(t)&&this.updateSelectedRangeStats(this.selection.startTime,this.selection.endTime);this.updateContents()}tabSelected(e){e.data.isUserGesture&&(this.setPreferredTab(e.data.tabId),this.updateContents())}layersView(){return this.lazyLayersView||(this.lazyLayersView=new ti(this.model.timelineModel(),this.showSnapshotInPaintProfiler.bind(this))),this.lazyLayersView}paintProfilerView(){return this.lazyPaintProfilerView||(this.lazyPaintProfilerView=new ri(this.model.frameModel())),this.lazyPaintProfilerView}showSnapshotInPaintProfiler(e){const t=this.paintProfilerView();t.setSnapshot(e),this.tabbedPane.hasTab(hi.PaintProfiler)||this.appendTab(hi.PaintProfiler,di(oi.paintProfiler),t,!0),this.tabbedPane.selectTab(hi.PaintProfiler,!0)}appendDetailsTabsForTraceEventAndShowDetails(e,t){this.setContent(t),n.TracingModel.eventIsFromNewEngine(e)||e.name!==r.TimelineModel.RecordType.Paint&&e.name!==r.TimelineModel.RecordType.RasterTask||this.showEventInPaintProfiler(e)}showEventInPaintProfiler(e){const t=n.TargetManager.TargetManager.instance().models(n.PaintProfiler.PaintProfilerModel)[0];if(!t)return;const i=this.paintProfilerView();i.setEvent(t,e)&&(this.tabbedPane.hasTab(hi.PaintProfiler)||this.appendTab(hi.PaintProfiler,di(oi.paintProfiler),i))}updateSelectedRangeStats(e,t){if(!this.model||!this.#f)return;const n=ct.statsForTimeRange(this.#f,e,t),r=e-this.model.timelineModel().minimumRecordTime(),a=t-this.model.timelineModel().minimumRecordTime(),s=new ft(null,null);s.addSection(di(oi.rangeSS,{PH1:i.TimeUtilities.millisToString(r),PH2:i.TimeUtilities.millisToString(a)}));const o=ct.generatePieChart(n);s.appendElementRow("",o),this.setContent(s.fragment)}}var hi;!function(e){e.Details="Details",e.EventLog="EventLog",e.CallTree="CallTree",e.BottomUp="BottomUp",e.PaintProfiler="PaintProfiler",e.LayerViewer="LayerViewer"}(hi||(hi={}));var mi=Object.freeze({__proto__:null,TimelineDetailsView:ci,get Tab(){return hi}});const ui={network:"Network"},pi=i.i18n.registerUIStrings("panels/timeline/TimelineFlameChartNetworkDataProvider.ts",ui),gi=i.i18n.getLocalizedString.bind(void 0,pi);class vi{#b;#C;#k;#P;#M;#E;#x;#I;#L;#R;#F;#D;#U;#H;#y;constructor(){this.#b=`${d.Font.DEFAULT_FONT_SIZE} ${d.Font.getFontFamilyForCanvas()}`,this.#C={padding:4,height:17,collapsible:!0,color:t.ThemeSupport.instance().getComputedValue("--color-text-primary"),font:this.#b,backgroundColor:t.ThemeSupport.instance().getComputedValue("--color-background"),nestingLevel:0,useFirstLineForOverview:!1,useDecoratorsForOverview:!0,shareHeaderLine:!1},this.#k={startLevel:0,name:gi(ui.network),expanded:!1,style:this.#C},this.#P=0,this.#M=0,this.#E=0,this.#x=[],this.#I=0,this.#L=null,this.#y=null,t.ThemeSupport.instance().addEventListener(t.ThemeChangeEvent.eventName,(()=>{this.#C.color=t.ThemeSupport.instance().getComputedValue("--color-text-primary"),this.#C.backgroundColor=t.ThemeSupport.instance().getComputedValue("--color-background")}))}setModel(e,t){this.#R=null,this.#L=e&&e.timelineModel(),this.#y=t}isEmpty(){return this.timelineData(),!this.#x.length}maxStackDepth(){return this.#I}timelineData(){return this.#R||(this.#x=[],this.#R=d.FlameChart.FlameChartTimelineData.createEmpty(),this.#L&&this.#N()),this.#R}minimumBoundary(){return this.#P}totalTime(){return this.#E}setWindowTimes(e,t){this.#F=e,this.#D=t,this.#A()}createSelection(e){if(-1===e)return null;const t=this.#x[e];return this.#U=new bi(De.fromNetworkRequest(t),e),this.#U.timelineSelection}entryIndexForSelection(e){if(!e)return-1;if(this.#U&&this.#U.timelineSelection.object===e.object)return this.#U.entryIndex;if(!De.isNetworkRequestSelection(e.object))return-1;const t=this.#x.indexOf(e.object);return-1!==t&&(this.#U=new bi(De.fromNetworkRequest(e.object),t)),t}entryColor(e){const t=this.#x[e],i=ct.networkRequestCategory(t);return ct.networkCategoryColor(i)}textColor(e){return Ci.textColor}entryTitle(e){const t=this.#x[e],i=new a.ParsedURL.ParsedURL(t.url||"");return i.isValid?`${i.displayName} (${i.host})`:t.url||null}entryFont(e){return this.#b}getDecorationPixels(e,t,i){const n=e.beginTime(),r=e=>Math.floor(t+(e-n)*i),a=e.getStartTime(),s=e.endTime,{sendStartTime:o,headersEndTime:l}=e.getSendReceiveTiming(),d=Math.max(r(o),t),c=Math.max(r(l),d),h=Math.max(r(e.finishTime||s),c+2);return{sendStart:d,headersEnd:c,finish:h,start:r(a),end:Math.max(r(s),h)}}decorateEntry(e,i,n,r,a,s,o,l,d){const h=this.#x[e];if(!h.timing)return!1;const{sendStart:m,headersEnd:u,finish:p,start:g,end:v}=this.getDecorationPixels(h,l,d);function T(e,t,n){i.moveTo(e,n-3),i.lineTo(e,n+3),i.moveTo(e,n),i.lineTo(t,n)}i.fillStyle="hsla(0, 100%, 100%, 0.8)",i.fillRect(m+.5,a+.5,u-m-.5,o-2),i.fillStyle=t.ThemeSupport.instance().getComputedValue("--color-background"),i.fillRect(r,a-.5,m-r,o),i.fillRect(p,a-.5,r+s-p,o),i.beginPath(),i.lineWidth=1,i.strokeStyle="#ccc";const f=Math.floor(a+o/2)+.5,w=v-.5;if(T(g+.5,m,f),T(w,p,f),i.stroke(),"string"==typeof h.priority){const e=this.#B(h.priority);e&&(i.fillStyle=e,i.fillRect(m+.5,a+.5,3.5,3.5))}const y=Math.max(m,0),S=p-y;if(S>=20){let t=this.entryTitle(e)||"";if(h.fromServiceWorker&&(t="⚙ "+t),t){const e=4,n=o-5,r=c.UIUtils.trimTextEnd(i,t,S-2*e);i.fillStyle="#333",i.fillText(r,y+e,a+n)}}return!0}forceDecoration(e){return!0}prepareHighlightedEntryInfo(e){const t=this.#x[e];if(!t.url)return null;const n=document.createElement("div"),r=c.Utils.createShadowRootWithCoreStyles(n,{cssFile:[R],delegatesFocus:void 0}).createChild("div","timeline-flamechart-popover"),a=t.getStartTime(),o=t.endTime-a;if(a&&isFinite(o)&&(r.createChild("span","timeline-info-network-time").textContent=i.TimeUtilities.millisToString(o,!0)),"string"==typeof t.priority){const e=r.createChild("span");e.textContent=d.NetworkPriorities.uiLabelForNetworkPriority(t.priority),e.style.color=this.#B(t.priority)||"black"}return r.createChild("span").textContent=s.StringUtilities.trimMiddle(t.url,80),n}#B(e){this.#H||(this.#H=new Map([["VeryLow",1],["Low",2],["Medium",3],["High",4],["VeryHigh",5]]));const t=this.#H.get(e);return t?`hsla(214, 80%, 50%, ${t/5})`:null}#N(){this.#L&&(this.#P=this.#L.minimumRecordTime(),this.#M=this.#L.maximumRecordTime(),this.#E=this.#L.isEmpty()?1e3:this.#M-this.#P,this.#L.networkRequests().forEach(this.#W.bind(this)),this.#A())}#A(){if(!this.#R)return;const e=[];let t=0;for(let i=0;i<this.#x.length;++i){const n=this.#x[i],r=n.beginTime(),a=this.#F;if(r<this.#D&&n.endTime>a){for(;e.length&&e[e.length-1]<=r;)e.pop();this.#R.entryLevels[i]=e.length,e.push(n.endTime),t=Math.max(t,e.length)}else this.#R.entryLevels[i]=-1}for(let e=0;e<this.#x.length;++e)-1===this.#R.entryLevels[e]&&(this.#R.entryLevels[e]=t);this.#R=d.FlameChart.FlameChartTimelineData.create({entryLevels:this.#R.entryLevels,entryTotalTimes:this.#R.entryTotalTimes,entryStartTimes:this.#R.entryStartTimes,groups:[this.#k]}),this.#I=t}#W(e){this.#x.push(e),this.#R.entryStartTimes.push(e.beginTime()),this.#R.entryTotalTimes.push(e.endTime-e.beginTime()),this.#R.entryLevels.push(this.#x.length-1)}preferredHeight(){return this.#C.height*(this.#k.expanded?s.NumberUtilities.clamp(this.#I+1,4,8.5):1)}isExpanded(){return this.#k&&Boolean(this.#k.expanded)}formatValue(e,t){return i.TimeUtilities.preciseMillisToString(e,t)}canJumpToEntry(e){return!1}navStartTimes(){return this.#L?this.#L.navStartTimes():new Map}}var Ti=Object.freeze({__proto__:null,TimelineFlameChartNetworkDataProvider:vi});const fi={sAtS:"{PH1} at {PH2}"},wi=i.i18n.registerUIStrings("panels/timeline/TimelineFlameChartView.ts",fi),yi=i.i18n.getLocalizedString.bind(void 0,wi);class Si extends c.Widget.VBox{delegate;model;searchResults;eventListeners;showMemoryGraphSetting;networkSplitWidget;mainDataProvider;mainFlameChart;networkFlameChartGroupExpansionSetting;networkDataProvider;networkFlameChart;networkPane;splitResizer;chartSplitWidget;countersView;detailsSplitWidget;detailsView;onMainEntrySelected;onNetworkEntrySelected;boundRefresh;#f;groupBySetting;searchableView;needsResizeToPreferredHeights;selectedSearchResult;searchRegex;#y;#e=null;constructor(e){super(),this.element.classList.add("timeline-flamechart"),this.delegate=e,this.model=null,this.eventListeners=[],this.#y=null,this.showMemoryGraphSetting=a.Settings.Settings.instance().createSetting("timelineShowMemory",!1),this.networkSplitWidget=new c.SplitWidget.SplitWidget(!1,!1,"timelineFlamechartMainView",150),this.networkSplitWidget.sidebarElement().style.zIndex="120";const t=a.Settings.Settings.instance().createSetting("timelineFlamechartMainViewGroupExpansion",{});this.mainDataProvider=new Ri,this.mainDataProvider.addEventListener(Hi.DataChanged,(()=>this.mainFlameChart.scheduleUpdate())),this.mainFlameChart=new d.FlameChart.FlameChart(this.mainDataProvider,this,t),this.mainFlameChart.alwaysShowVerticalScroll(),this.mainFlameChart.enableRuler(!1),this.networkFlameChartGroupExpansionSetting=a.Settings.Settings.instance().createSetting("timelineFlamechartNetworkViewGroupExpansion",{}),this.networkDataProvider=new vi,this.networkFlameChart=new d.FlameChart.FlameChart(this.networkDataProvider,this,this.networkFlameChartGroupExpansionSetting),this.networkFlameChart.alwaysShowVerticalScroll(),this.networkPane=new c.Widget.VBox,this.networkPane.setMinimumSize(23,23),this.networkFlameChart.show(this.networkPane.element),this.splitResizer=this.networkPane.element.createChild("div","timeline-flamechart-resizer"),this.networkSplitWidget.hideDefaultResizer(!0),this.networkSplitWidget.installResizer(this.splitResizer),this.networkSplitWidget.setMainWidget(this.mainFlameChart),this.networkSplitWidget.setSidebarWidget(this.networkPane),this.chartSplitWidget=new c.SplitWidget.SplitWidget(!1,!0,"timelineCountersSplitViewState"),this.countersView=new xt(this.delegate),this.chartSplitWidget.setMainWidget(this.networkSplitWidget),this.chartSplitWidget.setSidebarWidget(this.countersView),this.chartSplitWidget.hideDefaultResizer(),this.chartSplitWidget.installResizer(this.countersView.resizerElement()),this.updateCountersGraphToggle(),this.detailsSplitWidget=new c.SplitWidget.SplitWidget(!1,!0,"timelinePanelDetailsSplitViewState"),this.detailsSplitWidget.element.classList.add("timeline-details-split"),this.detailsView=new ci(e),this.detailsSplitWidget.installResizer(this.detailsView.headerElement()),this.detailsSplitWidget.setMainWidget(this.chartSplitWidget),this.detailsSplitWidget.setSidebarWidget(this.detailsView),this.detailsSplitWidget.show(this.element),this.onMainEntrySelected=this.onEntrySelected.bind(this,this.mainDataProvider),this.onNetworkEntrySelected=this.onEntrySelected.bind(this,this.networkDataProvider),this.mainFlameChart.addEventListener(d.FlameChart.Events.EntrySelected,this.onMainEntrySelected,this),this.mainFlameChart.addEventListener(d.FlameChart.Events.EntryInvoked,this.onMainEntrySelected,this),this.networkFlameChart.addEventListener(d.FlameChart.Events.EntrySelected,this.onNetworkEntrySelected,this),this.networkFlameChart.addEventListener(d.FlameChart.Events.EntryInvoked,this.onNetworkEntrySelected,this),this.mainFlameChart.addEventListener(d.FlameChart.Events.EntryHighlighted,this.onEntryHighlighted,this),this.boundRefresh=this.refresh.bind(this),this.#f=null,this.mainDataProvider.setEventColorMapping(ct.eventColor),this.groupBySetting=a.Settings.Settings.instance().createSetting("timelineTreeGroupBy",_t.GroupBy.None),this.groupBySetting.addChangeListener(this.updateColorMapper,this),this.updateColorMapper()}isNetworkTrackShownForTests(){return this.networkSplitWidget.showMode()!==c.SplitWidget.ShowMode.OnlyMain}updateColorMapper(){this.model&&(this.mainDataProvider.setEventColorMapping(ct.eventColor),this.mainFlameChart.update())}onWindowChanged(e){const{window:t,animate:i}=e.data;this.mainFlameChart.setWindowTimes(t.left,t.right,i),this.networkFlameChart.setWindowTimes(t.left,t.right,i),this.networkDataProvider.setWindowTimes(t.left,t.right),this.updateSearchResults(!1,!1)}windowChanged(e,t,i){this.model&&this.model.setWindow({left:e,right:t},i)}updateRangeSelection(e,t){this.delegate.select(De.fromRange(e,t))}updateSelectedGroup(e,t){e===this.mainFlameChart&&(this.#f=t?this.mainDataProvider.groupTreeEvents(t):null,this.updateTrack())}setModel(e,t,i){if(e!==this.model){if(this.#e=i,this.#y=t,a.EventTarget.removeEventListeners(this.eventListeners),this.model=e,this.#f=null,this.mainDataProvider.setModel(this.model,t,i),this.networkDataProvider.setModel(this.model,t),this.model){this.eventListeners=[this.model.addEventListener(Ct.WindowChanged,this.onWindowChanged,this)];const e=this.model.window();this.mainFlameChart.setWindowTimes(e.left,e.right),this.networkFlameChart.setWindowTimes(e.left,e.right),this.networkDataProvider.setWindowTimes(e.left,e.right),this.updateSearchResults(!1,!1)}this.updateColorMapper(),this.updateTrack(),this.refresh()}}updateTrack(){this.countersView.setModel(this.model,this.#f),this.detailsView.setModel(this.model,this.#y,this.#e,this.#f)}refresh(){this.networkDataProvider.isEmpty()?(this.mainFlameChart.enableRuler(!0),this.networkSplitWidget.hideSidebar()):(this.mainFlameChart.enableRuler(!1),this.networkSplitWidget.showBoth(),this.resizeToPreferredHeights()),this.mainFlameChart.reset(),this.networkFlameChart.reset(),this.updateSearchResults(!1,!1)}onEntryHighlighted(t){n.OverlayModel.OverlayModel.hideDOMNodeHighlight();const i=t.data,a=this.mainDataProvider.eventByIndex(i);if(!a)return;const s=this.model&&this.model.timelineModel().targetByEvent(a);if(!s)return;let o;if(a instanceof n.TracingModel.Event){o=r.TimelineModel.EventOnTimelineData.forEvent(a).backendNodeIds}else if(e.Types.TraceEvents.isTraceEventLayoutShift(a)){o=(a.args.data?.impacted_nodes??[]).map((e=>e.node_id))}if(o)for(let e=0;e<o.length;++e)new n.DOMModel.DeferredDOMNode(s,o[e]).highlight()}highlightEvent(e){const t=e?this.mainDataProvider.entryIndexForSelection(De.fromTraceEvent(e)):-1;t>=0?this.mainFlameChart.highlightEntry(t):this.mainFlameChart.hideHighlight()}willHide(){this.networkFlameChartGroupExpansionSetting.removeChangeListener(this.resizeToPreferredHeights,this),this.showMemoryGraphSetting.removeChangeListener(this.updateCountersGraphToggle,this),l.IgnoreListManager.IgnoreListManager.instance().removeChangeListener(this.boundRefresh)}wasShown(){this.networkFlameChartGroupExpansionSetting.addChangeListener(this.resizeToPreferredHeights,this),this.showMemoryGraphSetting.addChangeListener(this.updateCountersGraphToggle,this),l.IgnoreListManager.IgnoreListManager.instance().addChangeListener(this.boundRefresh),this.needsResizeToPreferredHeights&&this.resizeToPreferredHeights(),this.mainFlameChart.scheduleUpdate(),this.networkFlameChart.scheduleUpdate()}updateCountersGraphToggle(){this.showMemoryGraphSetting.get()?this.chartSplitWidget.showBoth():this.chartSplitWidget.hideSidebar()}setSelection(e){let t=this.mainDataProvider.entryIndexForSelection(e);this.mainFlameChart.setSelectedEntry(t),t=this.networkDataProvider.entryIndexForSelection(e),this.networkFlameChart.setSelectedEntry(t),this.detailsView&&this.detailsView.setSelection(e)}onEntrySelected(e,t){const i=t.data;o.Runtime.experiments.isEnabled("timelineEventInitiators")&&e===this.mainDataProvider&&this.mainDataProvider.buildFlowForInitiator(i)&&this.mainFlameChart.scheduleUpdate(),this.delegate.select(e.createSelection(i))}resizeToPreferredHeights(){this.isShowing()?(this.needsResizeToPreferredHeights=!1,this.networkPane.element.classList.toggle("timeline-network-resizer-disabled",!this.networkDataProvider.isExpanded()),this.networkSplitWidget.setSidebarSize(this.networkDataProvider.preferredHeight()+this.splitResizer.clientHeight+d.FlameChart.HeaderHeight+2)):this.needsResizeToPreferredHeights=!0}setSearchableView(e){this.searchableView=e}jumpToNextSearchResult(){if(!this.searchResults||!this.searchResults.length)return;const e=void 0!==this.selectedSearchResult?this.searchResults.indexOf(this.selectedSearchResult):-1;this.selectSearchResult(s.NumberUtilities.mod(e+1,this.searchResults.length))}jumpToPreviousSearchResult(){if(!this.searchResults||!this.searchResults.length)return;const e=void 0!==this.selectedSearchResult?this.searchResults.indexOf(this.selectedSearchResult):0;this.selectSearchResult(s.NumberUtilities.mod(e-1,this.searchResults.length))}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!0}selectSearchResult(e){this.searchableView.updateCurrentMatchIndex(e),this.searchResults&&(this.selectedSearchResult=this.searchResults[e],this.delegate.select(this.mainDataProvider.createSelection(this.selectedSearchResult)))}updateSearchResults(e,t){const i=this.selectedSearchResult;if(delete this.selectedSearchResult,this.searchResults=[],!this.searchRegex||!this.model)return;const n=new Ht(this.searchRegex),r=this.model.window();if(this.searchResults=this.mainDataProvider.search(r.left,r.right,n),this.searchableView.updateSearchMatchesCount(this.searchResults.length),!e||!this.searchResults.length)return;let a=this.searchResults.indexOf(i);-1===a&&(a=t?this.searchResults.length-1:0),this.selectSearchResult(a)}getSearchResults(){return this.searchResults}onSearchCanceled(){void 0!==this.selectedSearchResult&&this.delegate.select(null),delete this.searchResults,delete this.selectedSearchResult,delete this.searchRegex}performSearch(e,t,i){this.searchRegex=e.toSearchRegex().regex,this.updateSearchResults(t,i)}}class bi{timelineSelection;entryIndex;constructor(e,t){this.timelineSelection=e,this.entryIndex=t}}const Ci={textColor:"#333"};class ki{startTimeInternal;startOffset;style;constructor(e,t,i){this.startTimeInternal=e,this.startOffset=t,this.style=i}startTime(){return this.startTimeInternal}color(){return this.style.color}title(){if(this.style.lowPriority)return null;const e=i.TimeUtilities.millisToString(this.startOffset);return yi(fi.sAtS,{PH1:this.style.title,PH2:e})}draw(e,t,i,n){this.style.lowPriority&&n<4||(e.save(),this.style.tall&&(e.strokeStyle=this.style.color,e.lineWidth=this.style.lineWidth,e.translate(this.style.lineWidth<1||1&this.style.lineWidth?.5:0,.5),e.beginPath(),e.moveTo(t,0),e.setLineDash(this.style.dashStyle),e.lineTo(t,e.canvas.height),e.stroke()),e.restore())}}var Pi;!function(e){e.URL="URL"}(Pi||(Pi={}));var Mi=Object.freeze({__proto__:null,TimelineFlameChartView:Si,Selection:bi,FlameChartStyle:Ci,TimelineFlameChartMarker:ki,get ColorBy(){return Pi}});const Ei={onIgnoreList:"On ignore list",animation:"Animation",mainS:"Main — {PH1}",main:"Main",frameS:"Frame — {PH1}",subframe:"Subframe",raster:"Raster",rasterizerThreadS:"Rasterizer Thread {PH1}",thread:"Thread",frames:"Frames",sSelfS:"{PH1} (self {PH2})",idleFrame:"Idle Frame",droppedFrame:"Dropped Frame",partiallyPresentedFrame:"Partially Presented Frame",frame:"Frame",longFrame:"Long frame"},xi=i.i18n.registerUIStrings("panels/timeline/TimelineFlameChartDataProvider.ts",Ei),Ii=i.i18n.getLocalizedString.bind(void 0,xi),Li=e.Types.Timing.MilliSeconds(50);class Ri extends a.ObjectWrapper.ObjectWrapper{droppedFramePatternCanvas;partialFramePatternCanvas;timelineDataInternal;currentLevel;legacyPerformanceModel;compatibilityTracksAppender;legacyTimelineModel;traceEngineData;#e=null;#V=0;minimumBoundaryInternal;timeSpan;headerLevel1;headerLevel2;staticHeader;framesHeader;screenshotsHeader;animationsHeader;flowEventIndexById;entryData;entryTypeByLevel;screenshotImageCache;entryIndexToTitle;asyncColorByCategory;lastInitiatorEntry;entryParent;lastSelection;colorForEvent;#b;constructor(){super(),this.reset(),this.#b=`${d.Font.DEFAULT_FONT_SIZE} ${d.Font.getFontFamilyForCanvas()}`,this.droppedFramePatternCanvas=document.createElement("canvas"),this.partialFramePatternCanvas=document.createElement("canvas"),this.preparePatternCanvas(),this.timelineDataInternal=null,this.currentLevel=0,this.legacyPerformanceModel=null,this.legacyTimelineModel=null,this.compatibilityTracksAppender=null,this.traceEngineData=null,this.minimumBoundaryInternal=0,this.timeSpan=0,this.headerLevel1=this.buildGroupStyle({shareHeaderLine:!1}),this.headerLevel2=this.buildGroupStyle({padding:2,nestingLevel:1,collapsible:!1}),this.staticHeader=this.buildGroupStyle({collapsible:!1}),this.framesHeader=this.buildGroupStyle({useFirstLineForOverview:!0}),this.screenshotsHeader=this.buildGroupStyle({useFirstLineForOverview:!0,nestingLevel:1,collapsible:!1,itemsHeight:150}),this.animationsHeader=this.buildGroupStyle({useFirstLineForOverview:!1}),t.ThemeSupport.instance().addEventListener(t.ThemeChangeEvent.eventName,(()=>{const e=[this.headerLevel1,this.headerLevel2,this.staticHeader,this.framesHeader,this.screenshotsHeader,this.animationsHeader];for(const i of e)i.color=t.ThemeSupport.instance().getComputedValue("--color-text-primary"),i.backgroundColor=t.ThemeSupport.instance().getComputedValue("--color-background")})),this.flowEventIndexById=new Map}buildGroupStyle(e){const i={padding:4,height:17,collapsible:!0,color:t.ThemeSupport.instance().getComputedValue("--color-text-primary"),backgroundColor:t.ThemeSupport.instance().getComputedValue("--color-background"),nestingLevel:0,shareHeaderLine:!0};return Object.assign(i,e)}setModel(e,t,i){this.reset(),this.legacyPerformanceModel=e,this.legacyTimelineModel=e&&e.timelineModel(),this.traceEngineData=t,this.#e=i,this.legacyTimelineModel?(this.minimumBoundaryInternal=this.legacyTimelineModel.minimumRecordTime(),this.timeSpan=this.legacyTimelineModel.isEmpty()?1e3:this.legacyTimelineModel.maximumRecordTime()-this.minimumBoundaryInternal):this.traceEngineData&&this.setTimingBoundsData(this.traceEngineData)}setTimingBoundsData(t){const{traceBounds:i}=t.Meta,n=e.Helpers.Timing.microSecondsToMilliseconds(i.min),r=e.Helpers.Timing.microSecondsToMilliseconds(i.max);this.minimumBoundaryInternal=n,this.timeSpan=n===r?1e3:r-this.minimumBoundaryInternal}compatibilityTracksAppenderInstance(e=!1){if(!this.compatibilityTracksAppender||e){if(!this.traceEngineData||!this.legacyTimelineModel)throw new Error("Attempted to instantiate a CompatibilityTracksAppender without having set the trace parse data first.");this.timelineDataInternal=this.#O(),this.compatibilityTracksAppender=new en(this.timelineDataInternal,this.traceEngineData,this.entryData,this.entryTypeByLevel,this.legacyTimelineModel)}return this.compatibilityTracksAppender}#O(){return this.timelineDataInternal||(this.timelineDataInternal=d.FlameChart.FlameChartTimelineData.createEmpty()),this.timelineDataInternal}buildFromTrackAppenders(e){if(!this.compatibilityTracksAppender)return;const t=this.compatibilityTracksAppender.allVisibleTrackAppenders();for(const i of t){const t=e?.has(i.appenderName);this.currentLevel=i.appendTrackAtLevel(this.currentLevel,t)}}groupTrack(e){return e.track||null}groupTreeEvents(e){const t=this.compatibilityTracksAppender?.groupEventsForTreeView(e);return t||e.track?.eventsForTreeView()||null}navStartTimes(){return this.legacyTimelineModel?this.legacyTimelineModel.navStartTimes():new Map}entryTitle(e){const t=Ni,i=this.entryType(e);if(i===t.Event){const t=this.entryData[e];return"T"===t.phase||"p"===t.phase?t.name+":"+t.args.step:Di.get(t)?Ii(Ei.onIgnoreList):ct.eventTitle(t)}if(i===t.Screenshot)return"";if(i===t.TrackAppender){const t=this.timelineDataInternal.entryLevels[e],i=this.entryData[e];return this.compatibilityTracksAppender?.titleForEvent(i,t)||null}let n=this.entryIndexToTitle[e];return n||(n=`Unexpected entryIndex ${e}`,console.error(n)),n}textColor(e){const t=this.entryData[e];return t&&Di.get(t)?"#888":Ci.textColor}entryFont(e){return this.#b}reset(){this.currentLevel=0,this.timelineDataInternal=null,this.entryData=[],this.entryParent=[],this.entryTypeByLevel=[],this.entryIndexToTitle=[],this.asyncColorByCategory=new Map,this.screenshotImageCache=new Map,this.compatibilityTracksAppender=null}maxStackDepth(){return this.currentLevel}timelineData(){return this.timelineDataInternal&&0!==this.timelineDataInternal.entryLevels.length?this.timelineDataInternal:(this.timelineDataInternal=d.FlameChart.FlameChartTimelineData.createEmpty(),this.legacyTimelineModel?(this.flowEventIndexById.clear(),this.currentLevel=0,this.traceEngineData&&(this.compatibilityTracksAppender=this.compatibilityTracksAppenderInstance()),this.legacyTimelineModel.isGenericTrace()?this.processGenericTrace():this.processInspectorTrace(),this.timelineDataInternal):this.timelineDataInternal)}processGenericTrace(){const e=this.buildGroupStyle({shareHeaderLine:!1}),t=this.buildGroupStyle({padding:2,nestingLevel:1,shareHeaderLine:!1}),i=Ni.Event,n=new s.MapUtilities.Multimap;if(this.legacyTimelineModel){for(const e of this.legacyTimelineModel.tracks())null!==e.thread?n.set(e.thread.process(),e):console.error("Failed to process track");for(const a of n.keysArray()){if(n.size>1){const t=`${a.name()} ${a.id()}`;this.appendHeader(t,e,!1)}for(const e of n.get(a)){const n=this.appendSyncEvents(e,e.events,e.name,t,i,!0);!this.timelineDataInternal||this.timelineDataInternal.selectedGroup&&e.name!==r.TimelineModel.TimelineModelImpl.BrowserMainThreadName||(this.timelineDataInternal.selectedGroup=n)}}}}processInspectorTrace(){this.appendFrames();const e=e=>{if(void 0!==e.appenderName)switch(e.appenderName){case"Timings":return 1;case"Interactions":return 2;case"LayoutShifts":return 3;case"GPU":return 8;default:return-1}switch(e.type){case r.TimelineModel.TrackType.Animation:return 0;case r.TimelineModel.TrackType.MainThread:return e.forMainFrame?4:5;case r.TimelineModel.TrackType.Worker:return 6;case r.TimelineModel.TrackType.Raster:return 7;case r.TimelineModel.TrackType.Other:return 9;default:return-1}};if(!this.legacyTimelineModel)return;const t=this.compatibilityTracksAppender?this.compatibilityTracksAppender.allVisibleTrackAppenders():[],i=[...this.legacyTimelineModel.tracks(),...t].slice();i.sort(((t,i)=>e(t)-e(i)));for(const e of i)"type"in e?this.appendLegacyTrackData(e):this.traceEngineData&&(this.currentLevel=e.appendTrackAtLevel(this.currentLevel));this.timelineDataInternal&&this.timelineDataInternal.selectedGroup&&(this.timelineDataInternal.selectedGroup.expanded=!0),this.flowEventIndexById.clear()}#z(e,t){if(!this.timelineDataInternal)return;const i=this.timelineDataInternal.entryDecorations[e]||[];i.push(t),this.timelineDataInternal.entryDecorations[e]=i}appendLegacyTrackData(e,t){this.#O();const i=Ni.Event;switch(e.type){case r.TimelineModel.TrackType.Animation:this.appendAsyncEventsGroup(e,Ii(Ei.animation),e.asyncEvents,this.animationsHeader,i,!1,t);break;case r.TimelineModel.TrackType.MainThread:if(e.forMainFrame){const n=this.appendSyncEvents(e,e.events,e.url?Ii(Ei.mainS,{PH1:e.url}):Ii(Ei.main),this.headerLevel1,i,!0,t);n&&this.timelineDataInternal&&(this.timelineDataInternal.selectedGroup=n)}else this.appendSyncEvents(e,e.events,e.url?Ii(Ei.frameS,{PH1:e.url}):Ii(Ei.subframe),this.headerLevel1,i,!0,t);break;case r.TimelineModel.TrackType.Worker:this.appendSyncEvents(e,e.events,e.name,this.headerLevel1,i,!0,t);break;case r.TimelineModel.TrackType.Raster:this.#V||this.appendHeader(Ii(Ei.raster),this.headerLevel1,!1,t),++this.#V,this.appendSyncEvents(e,e.events,Ii(Ei.rasterizerThreadS,{PH1:this.#V}),this.headerLevel2,i,!0,t);break;case r.TimelineModel.TrackType.Other:this.appendSyncEvents(e,e.events,e.name||Ii(Ei.thread),this.headerLevel1,i,!0,t),this.appendAsyncEventsGroup(e,e.name,e.asyncEvents,this.headerLevel1,i,!0,t)}}minimumBoundary(){return this.minimumBoundaryInternal}totalTime(){return this.timeSpan}isEntryRegularEvent(e){return"name"in e}search(e,t,i){const r=[];this.timelineData();for(let a=0;a<this.entryData.length;++a){const s=this.entryData[a];if(!this.isEntryRegularEvent(s))continue;let o;if(s instanceof n.TracingModel.Event)o=s;else{if(!this.compatibilityTracksAppender){console.error("compatibilityTracksAppender was unexpectedly not set.");continue}o=this.compatibilityTracksAppender.getLegacyEvent(s)}o&&(o.startTime>t||(o.endTime||o.startTime)<e||i.accept(o)&&r.push(a))}return r.sort(((e,t)=>{let i=this.entryData[e],r=this.entryData[t];return this.isEntryRegularEvent(i)&&this.isEntryRegularEvent(r)?(i=i instanceof n.TracingModel.Event?i:this.compatibilityTracksAppender?.getLegacyEvent(i)||null,r=r instanceof n.TracingModel.Event?r:this.compatibilityTracksAppender?.getLegacyEvent(r)||null,i&&r?n.TracingModel.Event.compareStartTime(i,r):0):0})),r}appendSyncEvents(t,i,a,s,l,d,c){if(!i.length)return null;if(!this.legacyPerformanceModel||!this.legacyTimelineModel)return null;const h=[],m=o.Runtime.experiments.isEnabled("ignoreListJSFramesOnTimeline");let u=0,p=null;t&&t.type===r.TimelineModel.TrackType.MainThread&&(p=this.appendHeader(a,s,d,c),p.track=t);for(let o=0;o<i.length;++o){const l=i[o],{duration:g}=n.TracingModel.timesForEventInMilliseconds(l);if(this.legacyPerformanceModel){const e=this.legacyPerformanceModel.timelineModel().isInteractiveTimeEvent(l),i=this.legacyPerformanceModel.timelineModel().isLayoutShiftEvent(l),n=e||i;if(t&&t.type===r.TimelineModel.TrackType.MainThread&&n)continue}if(!e.Types.TraceEvents.isFlowPhase(l.phase)){if(!l.endTime&&"I"!==l.phase)continue;if(e.Types.TraceEvents.isAsyncPhase(l.phase))continue;if(!this.legacyPerformanceModel.isVisible(l))continue}for(;h.length&&h[h.length-1].endTime<=l.startTime;)h.pop();if(Di.set(l,!1),m&&this.isIgnoreListedEvent(l)){const e=h[h.length-1];if(e&&Di.get(e))continue;Di.set(l,!0)}!p&&a&&(p=this.appendHeader(a,s,d,c),d&&(p.track=t));const v=this.currentLevel+h.length,T=this.appendEvent(l,v);h.length&&(this.entryParent[T]=h[h.length-1]);Boolean(t?.forMainFrame&&t?.type===r.TimelineModel.TrackType.MainThread)&&l.name===r.TimelineModel.RecordType.Task&&g>Li&&this.#z(T,{type:"CANDY",startAtTime:e.Helpers.Timing.millisecondsToMicroseconds(Li)}),u=Math.max(u,h.length+1),l.endTime&&h.push(l)}return this.entryTypeByLevel.length=this.currentLevel+u,this.entryTypeByLevel.fill(l,this.currentLevel),this.currentLevel+=u,p}isIgnoreListedEvent(e){if(!r.TimelineModel.TimelineModelImpl.isJsFrameEvent(e))return!1;const t=e.args.data.url;return t&&this.isIgnoreListedURL(t)}isIgnoreListedURL(e){return l.IgnoreListManager.IgnoreListManager.instance().isUserIgnoreListedURL(e)}appendAsyncEventsGroup(e,t,i,n,r,a,s){if(!i.length)return null;const o=[];let l=null;for(let r=0;r<i.length;++r){const d=i[r];if(!this.legacyPerformanceModel||!this.legacyPerformanceModel.isVisible(d))continue;!l&&t&&(l=this.appendHeader(t,n,a,s),a&&(l.track=e));const c=d.startTime;let h;for(h=0;h<o.length&&o[h]>c;++h);this.appendAsyncEvent(d,this.currentLevel+h),o[h]=d.endTime}return this.entryTypeByLevel.length=this.currentLevel+o.length,this.entryTypeByLevel.fill(r,this.currentLevel),this.currentLevel+=o.length,l}appendFrames(){if(!this.legacyPerformanceModel||!this.timelineDataInternal||!this.legacyTimelineModel)return;const e=Boolean(this.#e&&this.#e.hasFrames());this.framesHeader.collapsible=e;const t="frames"===o.Runtime.Runtime.queryParam("flamechart-force-expand");this.appendHeader(Ii(Ei.frames),this.framesHeader,!1,t),this.entryTypeByLevel[this.currentLevel]=Ni.Frame;for(const e of this.legacyPerformanceModel.frames())this.appendFrame(e);if(++this.currentLevel,!this.#e||!e)return;let i;this.appendHeader("",this.screenshotsHeader,!1),this.entryTypeByLevel[this.currentLevel]=Ni.Screenshot;const n=this.#e.frames();for(const e of n)this.entryData.push(e),this.timelineDataInternal.entryLevels.push(this.currentLevel),this.timelineDataInternal.entryStartTimes.push(e.timestamp),i&&this.timelineDataInternal.entryTotalTimes.push(e.timestamp-i),i=e.timestamp;n.length&&void 0!==i&&this.timelineDataInternal.entryTotalTimes.push(this.legacyTimelineModel.maximumRecordTime()-i),++this.currentLevel}entryType(e){return this.entryTypeByLevel[this.timelineDataInternal.entryLevels[e]]}prepareHighlightedEntryInfo(e){let t,n,r="",a="timeline-info-time";const s=this.entryType(e);if(s===Ni.TrackAppender){if(!this.compatibilityTracksAppender)return null;const i=this.entryData[e],n=this.timelineDataInternal.entryLevels[e],a=this.compatibilityTracksAppender.highlightedEntryInfo(i,n);t=a.title,r=a.formattedTime}else if(s===Ni.Event){const a=this.entryData[e],s=a.duration,o=a.selfTime,d=1e-6;if("number"==typeof s&&(r=Math.abs(s-o)>d&&o>d?Ii(Ei.sSelfS,{PH1:i.TimeUtilities.millisToString(s,!0),PH2:i.TimeUtilities.millisToString(o,!0)}):i.TimeUtilities.millisToString(s,!0)),t=this.entryTitle(e),n=ct.eventWarning(a),this.legacyTimelineModel&&this.legacyTimelineModel.isParseHTMLEvent(a)){const e=a.args.beginData.startLine,i=a.args.endData&&a.args.endData.endLine;t+=` - ${l.ResourceUtils.displayNameForURL(a.args.beginData.url)} [${-1!==i||i===e?`${e}...${i}`:e}]`}}else{if(s!==Ni.Frame)return null;{const s=this.entryData[e];r=i.TimeUtilities.preciseMillisToString(s.duration,1),s.idle?t=Ii(Ei.idleFrame):s.dropped?(t=s.isPartial?Ii(Ei.partiallyPresentedFrame):Ii(Ei.droppedFrame),a="timeline-info-warning"):t=Ii(Ei.frame),s.hasWarnings()&&(n=document.createElement("span"),n.textContent=Ii(Ei.longFrame))}}const o=document.createElement("div"),d=c.Utils.createShadowRootWithCoreStyles(o,{cssFile:[R],delegatesFocus:void 0}).createChild("div","timeline-flamechart-popover");return d.createChild("span",a).textContent=r,d.createChild("span","timeline-info-title").textContent=t,n&&(n.classList.add("timeline-info-warning"),d.appendChild(n)),o}entryColor(t){if(!this.legacyPerformanceModel||!this.legacyTimelineModel)return"";const i=Ni,n=this.entryType(t);if(n===i.Event){const i=this.entryData[t];if(this.legacyTimelineModel.isGenericTrace())return this.genericTraceEventColor(i);if(this.legacyPerformanceModel.timelineModel().isMarkerEvent(i))return ct.markerStyleForEvent(i).color;if(!e.Types.TraceEvents.isAsyncPhase(i.phase)&&this.colorForEvent)return this.colorForEvent(i);const n=ct.eventStyle(i).category;return function(e,t,i){let n=e.get(t);if(n)return n;const r=a.Color.parse(i(t));if(!r)throw new Error("Could not parse color from entry");return n=r.setAlpha(.7).asString("rgba")||"",e.set(t,n),n}(this.asyncColorByCategory,n,(()=>n.color))}if(n===i.Frame)return"white";if(n===i.TrackAppender){const e=this.timelineDataInternal.entryLevels[t],i=this.entryData[t];return this.compatibilityTracksAppender?.colorForEvent(i,e)||""}return""}genericTraceEventColor(e){const t=e.categoriesString||e.name;return t?`hsl(${s.StringUtilities.hashCode(t)%300+30}, 40%, 70%)`:"#ccc"}preparePatternCanvas(){const e=17;this.droppedFramePatternCanvas.width=e,this.droppedFramePatternCanvas.height=e,this.partialFramePatternCanvas.width=e,this.partialFramePatternCanvas.height=e;const t=this.droppedFramePatternCanvas.getContext("2d");if(t){t.translate(8.5,8.5),t.rotate(.25*Math.PI),t.translate(-8.5,-8.5),t.fillStyle="rgb(255, 255, 255)";for(let e=-17;e<34;e+=3)t.fillRect(e,-17,1,51)}const i=this.partialFramePatternCanvas.getContext("2d");i&&(i.strokeStyle="rgb(255, 255, 255)",i.lineWidth=2,i.beginPath(),i.moveTo(17,0),i.lineTo(10,7),i.moveTo(8,9),i.lineTo(2,15),i.stroke())}drawFrame(e,t,n,r,a,s,o){const l=this.entryData[e];if(r+=1,s-=2,l.idle)t.fillStyle="white";else if(l.dropped)if(l.isPartial){t.fillStyle="#f0e442",t.fillRect(r,a,s,o);const e=t.createPattern(this.partialFramePatternCanvas,"repeat");t.fillStyle=e||t.fillStyle}else{t.fillStyle="#f08080",t.fillRect(r,a,s,o);const e=t.createPattern(this.droppedFramePatternCanvas,"repeat");t.fillStyle=e||t.fillStyle}else l.hasWarnings()?t.fillStyle="#fad1d1":t.fillStyle="#d7f0d1";t.fillRect(r,a,s,o);const d=i.TimeUtilities.preciseMillisToString(l.duration,1),c=t.measureText(d).width;c<=s&&(t.fillStyle=this.textColor(e),t.fillText(d,r+(s-c)/2,a+o-4))}async drawScreenshot(e,t,i,n,r,a){const s=this.entryData[e];if(!this.screenshotImageCache.has(s)){this.screenshotImageCache.set(s,null);const e=await s.imageDataPromise(),t=await c.UIUtils.loadImageFromData(e);return this.screenshotImageCache.set(s,t),void this.dispatchEventToListeners(Hi.DataChanged)}const o=this.screenshotImageCache.get(s);if(!o)return;const l=i+1,d=n+1,h=a-2,m=h/o.naturalHeight,u=Math.floor(o.naturalWidth*m);t.save(),t.beginPath(),t.rect(i,n,r,a),t.clip(),t.drawImage(o,l,d,u,h),t.strokeStyle="#ccc",t.strokeRect(l-.5,d-.5,Math.min(r-1,u+1),h),t.restore()}decorateEntry(e,t,i,n,a,s,o,l,d){const c=this.entryData[e],h=this.entryType(e),m=Ni;if(h===m.Frame)return this.drawFrame(e,t,i,n,a,s,o),!0;if(h===m.Screenshot)return this.drawScreenshot(e,t,n,a,s,o),!0;if(h===m.Event){const t=c;r.TimelineModel.EventOnTimelineData.forEvent(t).warning&&this.#z(e,{type:"WARNING_TRIANGLE"})}return!1}forceDecoration(e){const t=Ni,i=this.entryType(e);if(i===t.Frame)return!0;if(i===t.Screenshot)return!0;if(i===t.Event){const t=this.entryData[e];return Boolean(r.TimelineModel.EventOnTimelineData.forEvent(t).warning)}return!1}appendHeader(e,t,i,n){const r={startLevel:this.currentLevel,name:e,style:t,selectable:i,expanded:n};return this.timelineDataInternal.groups.push(r),r}appendEvent(e,t){const i=this.entryData.length;this.entryData.push(e);const n=this.timelineDataInternal;return n.entryLevels[i]=t,n.entryTotalTimes[i]=e.duration||Fi,n.entryStartTimes[i]=e.startTime,Ui.set(e,i),i}appendAsyncEvent(e,t){const i=e.steps,n=i.length>1&&"p"===i[1].phase?1:0;for(let e=0;e<i.length-1;++e){const r=this.entryData.length;this.entryData.push(i[e+n]);const a=i[e].startTime,s=this.timelineDataInternal;s.entryLevels[r]=t,s.entryTotalTimes[r]=i[e+1].startTime-a,s.entryStartTimes[r]=a}}appendFrame(e){const t=this.entryData.length;this.entryData.push(e),this.entryIndexToTitle[t]=i.TimeUtilities.millisToString(e.duration,!0),this.timelineDataInternal&&(this.timelineDataInternal.entryLevels[t]=this.currentLevel,this.timelineDataInternal.entryTotalTimes[t]=e.duration,this.timelineDataInternal.entryStartTimes[t]=e.startTime)}createSelection(e){const t=this.entryType(e);let i=null;const n=this.entryData[e];return n&&this.isEntryRegularEvent(n)?i=De.fromTraceEvent(n):t===Ni.Frame&&(i=De.fromFrame(this.entryData[e])),i&&(this.lastSelection=new bi(i,e)),i}formatValue(e,t){return i.TimeUtilities.preciseMillisToString(e,t)}canJumpToEntry(e){return!1}entryIndexForSelection(e){if(!e||De.isRangeSelection(e.object)||De.isNetworkRequestSelection(e.object))return-1;if(this.lastSelection&&this.lastSelection.timelineSelection.object===e.object)return this.lastSelection.entryIndex;const t=this.entryData.indexOf(e.object);return-1!==t&&(this.lastSelection=new bi(e,t)),t}buildFlowForInitiator(e){if(this.lastInitiatorEntry===e)return!1;this.lastInitiatorEntry=e;let t=this.eventByIndex(e);if(n.TracingModel.eventIsFromNewEngine(t))return!1;const i=this.timelineDataInternal;if(!i)return!1;for(i.flowStartTimes=[],i.flowStartLevels=[],i.flowEndTimes=[],i.flowEndLevels=[];t;){let e;for(;t&&(e=r.TimelineModel.EventOnTimelineData.forEvent(t).initiator(),!e);t=this.eventParent(t));if(!e||!t)break;const n=Ui.get(t),a=Ui.get(e);i.flowStartTimes.push(e.endTime||e.startTime),i.flowStartLevels.push(i.entryLevels[a]),i.flowEndTimes.push(t.startTime),i.flowEndLevels.push(i.entryLevels[n]),t=e}return!0}eventParent(e){const t=Ui.get(e);return void 0===t?null:this.entryParent[t]||null}eventByIndex(e){if(e<0)return null;const t=this.entryType(e);return t===Ni.TrackAppender||t===Ni.Event?this.entryData[e]:null}setEventColorMapping(e){this.colorForEvent=e}get performanceModel(){return this.legacyPerformanceModel}}const Fi=.001,Di=new WeakMap,Ui=new WeakMap;var Hi,Ni;!function(e){e.DataChanged="DataChanged"}(Hi||(Hi={})),function(e){e.Frame="Frame",e.Event="Event",e.TrackAppender="TrackAppender",e.Screenshot="Screenshot"}(Ni||(Ni={}));var Ai=Object.freeze({__proto__:null,TimelineFlameChartDataProvider:Ri,InstantEventVisibleDurationMs:Fi,get Events(){return Hi},get EntryType(){return Ni}});const Bi={timings:"Timings"},Wi=i.i18n.registerUIStrings("panels/timeline/TimingsTrackAppender.ts",Bi),Vi=i.i18n.getLocalizedString.bind(void 0,Wi);class Oi{appenderName="Timings";#s;#o;#l;#d;constructor(e,t,i,n){this.#o=e,this.#s=n,this.#l=t,this.#d=i}appendTrackAtLevel(e,t){const i=this.#d.PageLoadMetrics.allMarkerEvents,n=this.#d.UserTimings.performanceMarks,r=this.#d.UserTimings.performanceMeasures,a=this.#d.UserTimings.timestampEvents,s=this.#d.UserTimings.consoleTimings;if(0===i.length&&0===n.length&&0===r.length&&0===a.length&&0===s.length)return e;this.#c(e,t);let o=this.#G(e);return o=this.#o.appendEventsAtLevel(n,o,this),o=this.#o.appendEventsAtLevel(r,o,this),o=this.#o.appendEventsAtLevel(a,o,this),this.#o.appendEventsAtLevel(s,o,this)}#c(e,t){const i=b({shareHeaderLine:!0,useFirstLineForOverview:!0,collapsible:this.#d.UserTimings.performanceMeasures.length>0}),n=C(e,Vi(Bi.timings),i,!0,t);this.#o.registerTrackForGroup(n,this)}#G(t){const i=this.#d.PageLoadMetrics.allMarkerEvents;i.forEach((e=>{const i=this.#o.appendEventAtLevel(e,t,this);this.#l.entryTotalTimes[i]=Number.NaN}));const n=e.Helpers.Timing.microSecondsToMilliseconds(this.#d.Meta.traceBounds.min),r=i.map((t=>{const i=e.Helpers.Timing.microSecondsToMilliseconds(t.ts);return new ki(i,i-n,this.markerStyleForEvent(t))}));return this.#l.markers.push(...r),++t}markerStyleForEvent(t){let i="",n="grey";return e.Types.TraceEvents.isTraceEventMarkDOMContent(t)&&(n="#0867CB",i="DCL"),e.Types.TraceEvents.isTraceEventMarkLoad(t)&&(n="#B31412",i="L"),e.Types.TraceEvents.isTraceEventFirstPaint(t)&&(n="#228847",i="FP"),e.Types.TraceEvents.isTraceEventFirstContentfulPaint(t)&&(n="#1A6937",i="FCP"),e.Types.TraceEvents.isTraceEventLargestContentfulPaintCandidate(t)&&(n="#1A3422",i="LCP"),{title:i,dashStyle:[6,4],lineWidth:.5,color:n,tall:!0,lowPriority:!1}}colorForEvent(t){return e.Handlers.ModelHandlers.PageLoadMetrics.eventIsPageLoadEvent(t)?this.markerStyleForEvent(t).color:this.#s.colorForID(t.name)}titleForEvent(t){if(e.Handlers.ModelHandlers.PageLoadMetrics.eventIsPageLoadEvent(t))switch(t.name){case"MarkDOMContent":return"DCL";case"MarkLoad":return"L";case"firstContentfulPaint":return"FCP";case"firstPaint":return"FP";case"largestContentfulPaint::Candidate":return"LCP";default:return t.name}return e.Types.TraceEvents.isTraceEventTimeStamp(t)?`${t.name}: ${t.args.data.message}`:e.Types.TraceEvents.isTraceEventPerformanceMark(t)?`[mark]: ${t.name}`:t.name}highlightedEntryInfo(t){const i=this.titleForEvent(t);if(e.Handlers.ModelHandlers.PageLoadMetrics.isTraceEventMarkerEvent(t)||e.Types.TraceEvents.isTraceEventPerformanceMark(t)||e.Types.TraceEvents.isTraceEventTimeStamp(t)){return{title:i,formattedTime:k(e.Helpers.Timing.timeStampForEventAdjustedByClosestNavigation(t,this.#d.Meta.traceBounds,this.#d.Meta.navigationsByNavigationId,this.#d.Meta.navigationsByFrameId))}}return{title:i,formattedTime:k(t.dur)}}}var zi=Object.freeze({__proto__:null,TimingsTrackAppender:Oi});const Gi={gpu:"GPU"},_i=i.i18n.registerUIStrings("panels/timeline/GPUTrackAppender.ts",Gi),ji=i.i18n.getLocalizedString.bind(void 0,_i);class qi{appenderName="GPU";#o;#d;constructor(e,t){this.#o=e,this.#d=t}appendTrackAtLevel(e,t){const i=this.#d.GPU.mainGPUThreadTasks;return 0===i.length?e:(this.#c(e,t),this.#o.appendEventsAtLevel(i,e,this))}#c(e,t){const i=b({shareHeaderLine:!1}),n=C(e,ji(Gi.gpu),i,!0,t);this.#o.registerTrackForGroup(n,this)}colorForEvent(t){if(!e.Types.TraceEvents.isTraceEventGPUTask(t))throw new Error(`Unexpected GPU Task: The event's type is '${t.name}'`);return"hsl(109, 33%, 55%)"}titleForEvent(t){return e.Types.TraceEvents.isTraceEventGPUTask(t)?"GPU":t.name}highlightedEntryInfo(e){return{title:this.titleForEvent(e),formattedTime:k(e.dur)}}}var Ji=Object.freeze({__proto__:null,GPUTrackAppender:qi});const $i={layoutShifts:"Layout Shifts"},Xi=i.i18n.registerUIStrings("panels/timeline/LayoutShiftsTrackAppender.ts",$i),Yi=i.i18n.getLocalizedString.bind(void 0,Xi);class Ki{appenderName="LayoutShifts";#o;#l;#d;constructor(e,t,i){this.#o=e,this.#l=t,this.#d=i}appendTrackAtLevel(e,t){return 0===this.#d.LayoutShifts.clusters.length?e:(this.#c(e,t),this.#_(e))}#c(e,t){const i=b({collapsible:!1}),n=C(e,Yi($i.layoutShifts),i,!0,t);this.#o.registerTrackForGroup(n,this)}#_(t){const i=this.#d.LayoutShifts.clusters.flatMap((e=>e.events)),n=this.#o.appendEventsAtLevel(i,t,this),r=e.Types.Timing.MicroSeconds(5e3);for(let t=0;t<i.length;++t){const n=this.#o.indexForEvent(i[t]);void 0!==n&&(this.#l.entryTotalTimes[n]=e.Helpers.Timing.microSecondsToMilliseconds(r))}return n}colorForEvent(e){return"rgb(155 127 230)"}titleForEvent(t){return e.Types.TraceEvents.isTraceEventLayoutShift(t)?"Layout shift":t.name}highlightedEntryInfo(e){return{title:this.titleForEvent(e),formattedTime:k(e.dur)}}}var Zi=Object.freeze({__proto__:null,LayoutShiftsTrackAppender:Ki});const Qi=["Timings","Interactions","GPU","LayoutShifts"];class en{#j=new Map;#q=new Map;#J=new Map;#$=new Map;#l;#d;#X;#s;#Y=new WeakMap;#K=[];#Z=new Set([...Qi]);#L;#Q;#ee;#te;#ie;#ne;constructor(e,i,n,r,s){this.#l=e,this.#d=i,this.#X=n,this.#s=new a.Color.Generator({min:30,max:55,count:void 0},{min:70,max:100,count:6},50,.7),this.#Q=r,this.#L=s,this.#ee=new Oi(this,this.#l,this.#d,this.#s),this.#K.push(this.#ee),this.#te=new Ze(this,this.#l,this.#d,this.#s),this.#K.push(this.#te),this.#ie=new qi(this,this.#d),this.#K.push(this.#ie),this.#ne=new Ki(this,this.#l,this.#d),this.#K.push(this.#ne),t.ThemeSupport.instance().addEventListener(t.ThemeChangeEvent.eventName,(()=>{for(const e of this.#l.groups)e.style.color=t.ThemeSupport.instance().getComputedValue("--color-text-primary"),e.style.backgroundColor=t.ThemeSupport.instance().getComputedValue("--color-background")}))}getLegacyEvent(e){const t=this.#L.tracingModel()?.getProcessById(e.pid),i=t?.threadById(e.tid);return i?n.TracingModel.PayloadEvent.fromPayload(e,i):null}timingsTrackAppender(){return this.#ee}interactionsTrackAppender(){return this.#te}gpuTrackAppender(){return this.#ie}layoutShiftsTrackAppender(){return this.#ne}indexForEvent(e){return this.#Y.get(e)}eventsInTrack(e){const t=this.#J.get(e);if(t)return t;let i=null,n=null;for(const[t,r]of this.#j)r.appenderName===e&&(null===i&&(i=t),n=t);if(null===i||null===n)throw new Error(`Could not find events for track: ${e}`);const r=this.#l.entryLevels,a=[];for(let e=0;e<r.length;e++)i<=r[e]&&r[e]<=n&&a.push(this.#X[e]);return a.sort(((e,t)=>e.ts-t.ts)),this.#J.set(e,a),a}canBuildTreesFromEvents(e){const t=[];for(const i of e){const e=i.ts,n=i.ts+(i.dur||0);let r=t.at(-1);if(void 0===r){t.push(i);continue}let a=r.ts+(r.dur||0);for(;t.length&&e>=a&&(t.pop(),r=t.at(-1),void 0!==r);)a=r.ts+(r.dur||0);if(t.length&&n>a)return!1;t.push(i)}return!0}eventsForTreeView(t){const i=this.#$.get(t);if(i)return i;let n=this.eventsInTrack(t);return this.canBuildTreesFromEvents(n)||(n=n.filter((t=>!e.Types.TraceEvents.isAsyncPhase(t.ph)))),this.#$.set(t,n),n}registerTrackForGroup(e,t){this.#l.groups.push(e),this.#q.set(e,t)}groupEventsForTreeView(e){const t=this.#q.get(e);return t?this.eventsForTreeView(t.appenderName):null}registerTrackForLevel(e,t){this.#j.set(e,t)}appendEventAtLevel(t,i,n){this.#j.set(i,n);const r=this.#X.length;this.#X.push(t),this.#Y.set(t,r),this.#Q[i]=Ni.TrackAppender,this.#l.entryLevels[r]=i,this.#l.entryStartTimes[r]=e.Helpers.Timing.microSecondsToMilliseconds(t.ts);const a=t.dur||e.Helpers.Timing.millisecondsToMicroseconds(Fi);return this.#l.entryTotalTimes[r]=e.Helpers.Timing.microSecondsToMilliseconds(a),r}appendEventsAtLevel(e,t,i){const n=[];for(let a=0;a<e.length;++a){const s=e[a],o=this.getLegacyEvent(s),l=new Set(ct.visibleTypes());if(!(o&&l.has(r.TimelineModelFilter.TimelineVisibleEventsFilter.eventType(o))))continue;const d=P(s,n);this.appendEventAtLevel(s,t+d,i)}return this.#Q.length=t+n.length,this.#Q.fill(Ni.TrackAppender,t),t+n.length}allVisibleTrackAppenders(){return this.#K.filter((e=>this.#Z.has(e.appenderName)))}setVisibleTracks(e){this.#Z=e||new Set([...Qi])}colorForEvent(e,t){const i=this.#j.get(t);if(!i)throw new Error("Track not found for level");return i.colorForEvent(e)}titleForEvent(e,t){const i=this.#j.get(t);if(!i)throw new Error("Track not found for level");return i.titleForEvent(e)}highlightedEntryInfo(e,t){const i=this.#j.get(t);if(!i)throw new Error("Track not found for level");return i.highlightedEntryInfo(e)}}var tn=Object.freeze({__proto__:null,TrackNames:Qi,CompatibilityTracksAppender:en});export{M as AppenderUtils,L as CLSLinkifier,tn as CompatibilityTracksAppender,Ft as CountersGraph,ei as EventsTimelineTreeView,Ji as GPUTrackAppender,et as InteractionsTrackAppender,Zi as LayoutShiftsTrackAppender,kt as PerformanceModel,Re as SaveFileFormatter,O as TimelineController,mi as TimelineDetailsView,Q as TimelineEventOverview,Nt as TimelineFilters,Ai as TimelineFlameChartDataProvider,Ti as TimelineFlameChartNetworkDataProvider,Mi as TimelineFlameChartView,ce as TimelineHistoryManager,ii as TimelineLayersView,Te as TimelineLoader,si as TimelinePaintProfilerView,Je as TimelinePanel,Ue as TimelineSelection,$t as TimelineTreeView,St as TimelineUIUtils,zi as TimingsTrackAppender,Ee as UIDevtoolsController,Pe as UIDevtoolsUtils};
